Get free disk space

前端 未结 13 1599
孤街浪徒
孤街浪徒 2020-12-02 13:04

Given each of the inputs below, I\'d like to get free space on that location. Something like

long GetFreeSpace(string path)

Inputs:

13条回答
  •  感动是毒
    2020-12-02 13:20

    Here is a refactored and simplified version of the @sasha_gud answer:

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
            out ulong lpFreeBytesAvailable,
            out ulong lpTotalNumberOfBytes,
            out ulong lpTotalNumberOfFreeBytes);
    
        public static ulong GetDiskFreeSpace(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
    
            ulong dummy = 0;
    
            if (!GetDiskFreeSpaceEx(path, out ulong freeSpace, out dummy, out dummy))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
    
            return freeSpace;
        }
    

提交回复
热议问题