Reputation: 1
For an exercise I have to put the path of all the directories on my I:\ disk, the amount of files in those directories (and in their subfolders) and the size of the directory in a CSV-file. I've been able to write small pieces of code that give me a part of the solution.
With this code I'm able to get all the names of the directories.
static void Main(string[] args)
{
string importPath = string.Empty;
importPath = @"I:\";
foreach (string directory in Directory.EnumerateDirectories(importPath, "*.*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(directory);
}
Console.ReadLine();
}
And with this code I get all the info that I need to put in the CSV-file, but only from the I:\ disk and not it's directories.
static void Main(string[] args)
{
string importPath = string.Empty;
importPath = @"I:\";
DirectoryInfo dInfo = new DirectoryInfo(importPath);
double sizeOfDir = DirectorySize(dInfo, true);
DirectoryInfo d = new DirectoryInfo(importPath);
FileInfo[] f = d.GetFiles("*", SearchOption.AllDirectories);
System.Console.WriteLine(dInfo.FullName + "; " + f.Length.ToString() + "; " +
string.Format("{0:0.00}", ((double)sizeOfDir) / (1024 * 1024 * 1024)) + "GB");
System.Console.ReadLine();
}
private static double DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
{
double totalSize = dInfo.EnumerateFiles()
.Sum(file => file.Length);
if (includeSubDir)
{
totalSize += dInfo.EnumerateDirectories()
.Sum(dir => DirectorySize(dir, true));
}
return totalSize;
}
I don't know how I can combine these 2 or if I have to do something totally different. An example of what I should get in the end is:
I:\Scanner; 1543; 100GB
I:\Printer; 296; 22GB
I:\SysDeploy; 935; 66GB
I:\Intern; 4256; 30GB
Upvotes: 0
Views: 716
Reputation: 5566
Use Directory.GetDirectories
to get all directories including sub directories
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getdirectories?view=net-7.0
string[] dirs = Directory.GetDirectories(@"i:\", "*", SearchOption.AllDirectories);
You can then loop through the paths getting the DirectoryInfo for each directory:
DirectoryInfo di = new DirectoryInfo(path);
However be carfull running this on the root of a big drive (e.g. c:\) as this could take a while.
Upvotes: 1