开发者

total size and number of files by type in C#

开发者 https://www.devze.com 2023-03-28 13:03 出处:网络
I\'m a Java vet but new to .NET.I need to gather a total size and number of files by type and a grand total in C#.Is there a better way than a recursive search? Also, I need to find multiple types.Wou

I'm a Java vet but new to .NET. I need to gather a total size and number of files by type and a grand total in C#. Is there a better way than a recursive search? Also, I need to find multiple types. Would HashTable be appropriate to load with my extensions and update?

void DirSearc开发者_高级运维h(string sDir) 
{
try 
{
   foreach (string d in Directory.GetDirectories(sDir)) 
   {
    FileInfo[] fiArr = d.GetFiles();
    foreach (string f in fiArr) 
    {
       String ext = Path.GetExtension(f.Name);
       if (myht.ContainsKey(ext)
       {
        myht[ext] = myht[ext] + f.Length;
       }
    }
    DirSearch(d);
   }
}
catch (System.Exception excpt) 
{
    Console.WriteLine(excpt.Message);
}
}


You should call Directory.EnumerateFiles(sDir, SearchOption.AllDirectories)


The general approach has been outlined by @Slaks - since you do need to support a set of different file extensions though and want to get statistics it might be better to write a custom method so you only have to walk over the directory tree once.

Instead of using recursive calls you can just use a Stack to express the recursion, below just an example that returns a list of matching files based on an enumeration of extensions - you can easily modify this for your scenario:

public static List<string> DirSearch(string startDirectory, IEnumerable<string> extensions)
{
    Stack<string> directoryStack = new Stack<string>();
    List<string> files = new List<string>();

    directoryStack.Push(startDirectory);
    while (directoryStack.Count > 0)
    {
        string currentDirectory = directoryStack.Pop();
        DirectoryInfo di = new DirectoryInfo(currentDirectory);
        files.AddRange(di.EnumerateFiles()
                         .Where(f => extensions.Contains(f.Extension))
                         .Select(f => f.FullName));
        foreach (string directory in Directory.GetDirectories(currentDirectory))
            directoryStack.Push(directory);
    }
    return files;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号