30. Directory size

The following extension method returns the size of a directory's contents:

// Calculate the directory's size.
public static long Size(this DirectoryInfo dirinfo,
bool includeSubdirs = false)
{
// Get the files within the directory.
FileInfo[] fileinfos;
if (includeSubdirs)
fileinfos = dirinfo.GetFiles("*", SearchOption.AllDirectories);
else
fileinfos = dirinfo.GetFiles("*",
SearchOption.TopDirectoryOnly);

    // Add the file sizes.
long size = 0;
foreach (FileInfo fileinfo in fileinfos) size += fileinfo.Length;

return size;
}

This method calls the DirectoryInfo object's GetFiles method to get information on the files contained within the directory. Depending on the value of its includeSubdirs parameter, the method either tells GetFiles to consider only files directly contained in the directory or to consider files in the directory's subdirectories.

The method then simply loops through the returned files and adds their sizes. It finishes by returning the total file size.

Download the DirectorySize example solution to see additional details.

The program uses the following ToFileSize extension method to format value in file units as in 24.1 KB:

[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
public static extern Int32 StrFormatByteSize(long fileSize,
[MarshalAs(UnmanagedType.LPTStr)]
StringBuilder buffer, int bufferSize);

// Use the StrFormatByteSize API function to convert
// a number of bytes into a file size.
public static string ToFileSize(this long fileSize)
{
StringBuilder sb = new StringBuilder(20);
StrFormatByteSize(fileSize, sb, 20);
return sb.ToString();
}

This code imports the Windows StrFormatByteSize API function. The ToFileSize method simply uses that function to format a long value in file units and returns the result.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.36.41