如何通过C#获得未标记的卷驱动器总大小?

时间:2015-06-17 17:20:34

标签: c# windows diskspace disk-partitioning driveinfo

我使用C#来调查Windows驱动器。

如何使用RAW分区获取音量大小?

1 个答案:

答案 0 :(得分:1)

首先要表示一个音量:

public class Volume
{
    public Volume(string path)
    {
        Path = path;
        ulong freeBytesAvail, totalBytes, totalFreeBytes;
        if (GetDiskFreeSpaceEx(path, out freeBytesAvail, out totalBytes, out totalFreeBytes))
        {
            FreeBytesAvailable = freeBytesAvail;
            TotalNumberOfBytes = totalBytes;
            TotalNumberOfFreeBytes = totalFreeBytes;
        }
    }

    public string Path { get; private set; }

    public ulong FreeBytesAvailable { get; private set; }
    public ulong TotalNumberOfBytes { get; private set; }     
    public ulong TotalNumberOfFreeBytes { get; private set; }

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool GetDiskFreeSpaceEx([MarshalAs(UnmanagedType.LPStr)]string volumeName, out ulong freeBytesAvail,
        out ulong totalBytes, out ulong totalFreeBytes);
}

接下来有一个简单的卷枚举器:

public class VolumeEnumerator : IEnumerable<Volume>
{
    public IEnumerator<Volume> GetEnumerator()
    {
        StringBuilder sb = new StringBuilder(2048);
        IntPtr volumeHandle = FindFirstVolume(sb, (uint)sb.MaxCapacity);
        {
            if (volumeHandle == IntPtr.Zero)
                yield break;
            else
            {
                do
                {
                    yield return new Volume(sb.ToString());
                    sb.Clear();
                }
                while (FindNextVolume(volumeHandle, sb, (uint)sb.MaxCapacity));
                FindVolumeClose(volumeHandle);
            }
        }

    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr FindFirstVolume([Out] StringBuilder lpszVolumeName,
       uint cchBufferLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool FindNextVolume(IntPtr hFindVolume, [Out] StringBuilder lpszVolumeName, uint cchBufferLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool FindVolumeClose(IntPtr hFindVolume);
}

最后使用它的示例代码:

foreach (Volume v in new VolumeEnumerator())
{
    Console.WriteLine("{0}, Free bytes available {1} Total Bytes {2}", v.Path,
        v.FreeBytesAvailable, v.TotalNumberOfBytes);
}

这是将P / Invokes构建到Volume Management API。如果这不是你想要的,你可能会在那里找到具体的信息。