C# Get file size of array with paths
Asked Answered
S

5

9

I am new to arrays and I want to display the size (in MB) of multiple files into a textBox. The paths to the files are in an array.

var Files = Directory.GetFiles(Path, "*" + filetype, SearchOption.AllDirectories);

I saw this code in another post to get the size of a file:

long length = new System.IO.FileInfo(file).Length;

How can I add all of the file sizes to an int/string and write them into the textBox?

Spidery answered 8/8, 2018 at 6:32 Comment(2)
MB is just FileInfoLength / (1024*1024)Eanes
@loyd, does the below answers solve your problem or not?Ammonify
M
7

If i understand you correctly, just use Linq Select and string.Join

var results = Directory.GetFiles(Path, "*" + filetype, SearchOption.AllDirectories)
                        .Select(file => new FileInfo(file).Length);

 TextBox1.Text = string.Join(", ", results);

if you want to sum them, just use Enumerable.Sum

 TextBox1.Text = $"{results.Sum():N3}";

Update

public static class MyExtension
{
    public enum SizeUnits
    {
        Byte, KB, MB, GB, TB, PB, EB, ZB, YB
    }

    public static string ToSize(this Int64 value, SizeUnits unit)
    {
        return (value / (double)Math.Pow(1024, (Int64)unit)).ToString("0.00");
    }
}

 TextBox1.Text = results.Sum().ToSize();
Mainsail answered 8/8, 2018 at 6:35 Comment(4)
One more question, is there a way to get a decimal value? In my case a file has the size of 14.9 MB but I end up with 14 MB.Spidery
@Spidery you can read more about them here learn.microsoft.com/en-us/dotnet/standard/base-types/…Mainsail
I used $"{results.Sum() / (1024*1024):N3}"; to get the file size in MB but the decimal value gets filled with zeros only. What is my mistake?Spidery
@Spidery you could use $"{results.Sum() / (double)(1024*1024):N3}", or i updated my answer if you want to get fancyMainsail
N
2

If you don't want to add complexity by using LINQ and want to practice with arrays:

var Files = Directory.GetFiles(Path, "*" + filetype, SearchOption.AllDirectories);

long length = 0;

for (int i = 0; i < Files.Length; i++)
{
    length += new FileInfo(Files[i]).Length;
}
Noelyn answered 8/8, 2018 at 6:37 Comment(0)
M
0

The below code may work to you.

var FilesAndSizes = Directory.GetFiles(Path, "*" + filetype, SearchOption.AllDirectories).Select(item => new KeyValuePair<string,int>(item, new System.IO.FileInfo(item).Length));
Micheal answered 8/8, 2018 at 6:40 Comment(0)
C
0

Using Directory.EnumerateFiles you're able to calculate the total size while only traversing the array once.

To get the total size for all files of an extension:

long totalSizeInBytes = 0;
foreach(var file in Directory.EnumerateFiles(Path, "*" + filetype, SearchOption.AllDirectories))
{                
    totalSizeInBytes += new FileInfo(file).Length;
}

To get a list of all file sizes:

var results = Directory.EnumerateFiles(Path, "*" + filetype, SearchOption.AllDirectories)
                    .Select(file => new FileInfo(file).Length);

TextBox1.Text = string.Join(", ", results);
Conan answered 8/8, 2018 at 7:11 Comment(0)
P
0

i think that DirectoryInfo object cuold be smarter for your case istead of Directory object.

Look at that example:

public static void Main()
{
    string filetype = ".jpg";

    // Make a reference to a directory.
    DirectoryInfo di = new DirectoryInfo("c:\\");
    // Get a reference to each file in that directory.
    FileInfo[] fiArr = di.GetFiles("*" + filetype, SearchOption.AllDirectories);
    // Display the names and sizes of the files.
    Console.WriteLine("The directory {0} contains the following files:", di.Name);
    foreach (FileInfo f in fiArr)
        Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
}

the GetFiles method returns an array of FileInfo objects, where you can find the filesize.

Parameters:

I this example i'm writing to console output but in the same way you can add the text to your textbox.

   mytexbox.Text += String.Format("The size of {0} is {1} bytes.\r\n", f.Name, f.Length);
Playbill answered 8/8, 2018 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.