【问题标题】:How can I get unlabeled volume drive total size by C#?如何通过 C# 获取未标记的卷驱动器总大小?
【发布时间】:2015-09-03 01:59:19
【问题描述】:

我正在使用 C# 来研究 Windows 驱动器。

如何使用 RAW Partition 获取卷的大小?

【问题讨论】:

标签: c# windows diskspace disk-partitioning driveinfo


【解决方案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 中。如果这不是您想要的,您可能会在那里找到具体信息。

【讨论】:

  • 谢谢,但没用。它向我显示了有关 ntfs 的正确信息,但对于所有 RAW 分区,它向我显示“可用的可用字节数 0 Total Bytes 0”。
  • @user436862 因为未分配的分区没有可用的字节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多