Directory file size calculation - how to make it faster?

前端 未结 8 1425
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 11:10

Using C#, I am finding the total size of a directory. The logic is this way : Get the files inside the folder. Sum up the total size. Find if there are sub directories. Then

8条回答
  •  醉话见心
    2020-12-08 11:28

    If fiddled with it a while, trying to Parallelize it, and surprisingly - it speeded up here on my machine (up to 3 times on a quadcore), don't know if it is valid in all cases, but give it a try...

    .NET4.0 Code (or use 3.5 with TaskParallelLibrary)

        private static long DirSize(string sourceDir, bool recurse)
        {
            long size = 0;
            string[] fileEntries = Directory.GetFiles(sourceDir);
    
            foreach (string fileName in fileEntries)
            {
                Interlocked.Add(ref size, (new FileInfo(fileName)).Length);
            }
    
            if (recurse)
            {
                string[] subdirEntries = Directory.GetDirectories(sourceDir);
    
                Parallel.For(0, subdirEntries.Length, () => 0, (i, loop, subtotal) =>
                {
                    if ((File.GetAttributes(subdirEntries[i]) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
                    {
                        subtotal += DirSize(subdirEntries[i], true);
                        return subtotal;
                    }
                    return 0;
                },
                    (x) => Interlocked.Add(ref size, x)
                );
            }
            return size;
        }
    

提交回复
热议问题