Get free disk space

前端 未结 13 1588
孤街浪徒
孤街浪徒 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:34

    I wanted a similar method for my project but in my case the input paths were either from local disk volumes or clustered storage volumes (CSVs). So DriveInfo class did not work for me. CSVs have a mount point under another drive, typically C:\ClusterStorage\Volume*. Note that C: will be a different Volume than C:\ClusterStorage\Volume1

    This is what I finally came up with:

        public static ulong GetFreeSpaceOfPathInBytes(string path)
        {
            if ((new Uri(path)).IsUnc)
            {
                throw new NotImplementedException("Cannot find free space for UNC path " + path);
            }
    
            ulong freeSpace = 0;
            int prevVolumeNameLength = 0;
    
            foreach (ManagementObject volume in
                    new ManagementObjectSearcher("Select * from Win32_Volume").Get())
            {
                if (UInt32.Parse(volume["DriveType"].ToString()) > 1 &&                             // Is Volume monuted on host
                    volume["Name"] != null &&                                                       // Volume has a root directory
                    path.StartsWith(volume["Name"].ToString(), StringComparison.OrdinalIgnoreCase)  // Required Path is under Volume's root directory 
                    )
                {
                    // If multiple volumes have their root directory matching the required path,
                    // one with most nested (longest) Volume Name is given preference.
                    // Case: CSV volumes monuted under other drive volumes.
    
                    int currVolumeNameLength = volume["Name"].ToString().Length;
    
                    if ((prevVolumeNameLength == 0 || currVolumeNameLength > prevVolumeNameLength) &&
                        volume["FreeSpace"] != null
                        )
                    {
                        freeSpace = ulong.Parse(volume["FreeSpace"].ToString());
                        prevVolumeNameLength = volume["Name"].ToString().Length;
                    }
                }
            }
    
            if (prevVolumeNameLength > 0)
            {
                return freeSpace;
            }
    
            throw new Exception("Could not find Volume Information for path " + path);
        }
    

提交回复
热议问题