Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get file size of array with paths

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?

like image 651
loyd Avatar asked Aug 08 '18 06:08

loyd


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

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();
like image 109
TheGeneral Avatar answered Oct 14 '22 11:10

TheGeneral