Monday, August 25, 2014

file size


Here is a function that uses recursion (Hidden in the LINQ statement) to calculate the size of a given directory:



// Usage: GetDirectorySize("C:/");
public static long GetDirectorySize(string path)
{
return GetDirectorySize(new DirectoryInfo(path));
}

public static long GetDirectorySize(DirectoryInfo directoryInfo)
{
// Calculate the size of all files in the current directory
var sizeOfFiles = directoryInfo.GetFiles().Sum(fileInfo => fileInfo.Length);

// Now calculate the size of each child directory, and sum them to get the size of child directories
var sizeOfDirectories = directoryInfo.GetDirectories().Select(GetDirectorySize).Sum();

// The size of a directory is the size of its files + the size of child directories
return sizeOfFiles + sizeOfDirectories;
}



Using this you can simply supply the path as either a DirectoryInfo object or as a string.


Well if i use this: c:/users... It gives me an error: no acces to this location..


So don't think this is works.


Also i can just use driveinfo if the user selected like: C:/..


I only need to use directoryinfo if the selected location is a subfolder..








The program either needs to be ran as an Administrator, or you can add exception handling to prevent the program from crashing. I suggest adding exception handling to your code regardless.


If you want to use the values from DriveInfo then you can check if the directory path is the same as a drive, if so return the size.


No comments:

Post a Comment