Ben
Ben

Reputation: 45

Total size of all files

I'm writing a console application and i want it to display the total size of all the files in a certain directory an example of the output would be this

Files in: C:\Windows
Total files: 49
Total size of all files: 7121424 bytes

Here is what i currently have:

            if (menuOption == "3")
        {
            Console.Clear();
            Console.WriteLine("Files in C:\\windows");
            Console.WriteLine("");
            DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
            FileInfo[] files = folderInfo.GetFiles();

            for (numFiles = 0; numFiles < files.Length; numFiles++)
            { 
            }
            Console.Write("Total Files: {0}",numFiles);
        }

As you can see i have already made it so that it gets the total amount of files in C:\Windows but im unsure how to make it add all the file sizes together. Hope you guys can give me some insight, thanks.

Upvotes: 0

Views: 912

Answers (2)

t3chb0t
t3chb0t

Reputation: 18675

By using the FileInfo.Length Property

long totalFileSize = 0;
for (numFiles = 0; numFiles < files.Length; numFiles++)
{
    totalFileSize += files[numFiles].Length;
}

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Use Length property of FileInfo

var totalSize = files.Sum(x => x.Length);

Upvotes: 6

Related Questions