Directory file size calculation - how to make it faster?

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

    I gave up on the .NET implementations (for performance reasons) and used the Native function GetFileAttributesEx(...)

    Try this:

    [StructLayout(LayoutKind.Sequential)]
    public struct WIN32_FILE_ATTRIBUTE_DATA
    {
        public uint fileAttributes;
        public System.Runtime.InteropServices.ComTypes.FILETIME creationTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME lastAccessTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME lastWriteTime;
        public uint fileSizeHigh;
        public uint fileSizeLow;
    }
    
    public enum GET_FILEEX_INFO_LEVELS
    {
        GetFileExInfoStandard,
        GetFileExMaxInfoLevel
    }
    
    public class NativeMethods {
        [DllImport("KERNEL32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetFileAttributesEx(string path, GET_FILEEX_INFO_LEVELS  level, out WIN32_FILE_ATTRIBUTE_DATA data);
    
    }
    

    Now simply do the following:

    WIN32_FILE_ATTRIBUTE_DATA data;
    if(NativeMethods.GetFileAttributesEx("[your path]", GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out data)) {
    
         long size = (data.fileSizeHigh << 32) & data.fileSizeLow;
    }
    

提交回复
热议问题