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?

2
  • MB is just FileInfoLength / (1024*1024)
    – fubo
    Aug 8, 2018 at 6:43
  • @loyd, does the below answers solve your problem or not?
    – er-sho
    Aug 8, 2018 at 6:53

5 Answers 5

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();
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.
    – loyd
    Aug 8, 2018 at 8:24
  • 1
    @loyd you can read more about them here learn.microsoft.com/en-us/dotnet/standard/base-types/…
    – TheGeneral
    Aug 8, 2018 at 8:26
  • 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?
    – loyd
    Aug 8, 2018 at 9:49
  • 1
    @loyd you could use $"{results.Sum() / (double)(1024*1024):N3}", or i updated my answer if you want to get fancy
    – TheGeneral
    Aug 8, 2018 at 9:50
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;
}
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));
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);
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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.