Directory file size calculation - how to make it faster?

前端 未结 8 1426
没有蜡笔的小新
没有蜡笔的小新 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:39

    Based on the answer by spookycoder, I found this variation (using DirectoryInfo) at least 2 times faster (and up to 10 times faster on complex folder structures!) :

        public static long CalcDirSize(string sourceDir, bool recurse = true)
        {
            return _CalcDirSize(new DirectoryInfo(sourceDir), recurse);
        }
    
        private static long _CalcDirSize(DirectoryInfo di, bool recurse = true)
        {
            long size = 0;
            FileInfo[] fiEntries = di.GetFiles();
            foreach (var fiEntry in fiEntries)
            {
                Interlocked.Add(ref size, fiEntry.Length);
            }
    
            if (recurse)
            {
                DirectoryInfo[] diEntries = di.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
                System.Threading.Tasks.Parallel.For(0, diEntries.Length, () => 0, (i, loop, subtotal) =>
                {
                    if ((diEntries[i].Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) return 0;
                    subtotal += __CalcDirSize(diEntries[i], true);
                    return subtotal;
                },
                    (x) => Interlocked.Add(ref size, x)
                );
    
            }
            return size;
        }
    

提交回复
热议问题