从远程计算机获取驱动器信息。

11

我可以从这篇使用C#远程桌面文章中查看连接到远程计算机,但我并不需要这个功能。我只需要连接到该计算机并获取C盘的可用空间数据。如何实现?我可以连接到远程桌面,使用IO命名空间获取DriveInfo,但如何将它们结合起来呢?


如果您不需要远程桌面,为什么要使用远程桌面客户端呢?我建议您查看WMI - 可以参考这个问题 - Bridge
3个回答

26

使用System.Management命名空间Win32_Volume WMI类来完成此操作。您可以查询一个具有C:驱动器号的实例,并按以下方式检索其FreeSpace属性:

ManagementPath path = new ManagementPath() {
    NamespacePath = @"root\cimv2",
    Server = "<REMOTE HOST OR IP>"
};
ManagementScope scope = new ManagementScope(path);
string condition = "DriveLetter = 'C:'";
string[] selectedProperties = new string[] { "FreeSpace" };
SelectQuery query = new SelectQuery("Win32_Volume", condition, selectedProperties);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
using (ManagementObjectCollection results = searcher.Get())
{
    ManagementObject volume = results.Cast<ManagementObject>().SingleOrDefault();

    if (volume != null)
    {
        ulong freeSpace = (ulong) volume.GetPropertyValue("FreeSpace");

        // Use freeSpace here...
    }
}

此外,还有一个Capacity属性,用于存储卷的总大小。


1
我在路径中不需要通过任何身份验证吗? - user1865670
2
这取决于您的环境。可以使用scope.Options属性来设置凭据和其他安全选项,该属性是ConnectionOptions类的一个实例。 - Lance U. Matthews
什么是freeSpace?它是以比特为单位吗? - Si8
我发现它是以字节为单位的。但信息不准确。例如,服务器上C盘有56.5GB可用空间,但代码显示62GB。 - Si8
2
@Si8 你从哪里获取“准确”的可用空间信息?是从Windows资源管理器中获取的吗?你是使用freeSpace / 1024 / 1024 / 1024还是freeSpace / 1000 / 1000 / 1000来计算可用的GB数? - Lance U. Matthews
是的...我+1了,因为我之前使用谷歌的转换器时出现了问题,但当我应用正确的计算方法后,它就正常工作了。谢谢。 - Si8

0
在浪费一整天的时间尝试远程使用WMI无果后,我发现了一种使用性能计数器的替代方法。只需检查LogicalDisk类别中以所需驱动器字母(附加“:”)作为实例名称的Free Megabytes计数器,即可获得驱动器可用空间的最新读数:
"LogicalDisk(C:)\Free Megabytes"

你可以通过 PerformanceCounter Class 在 C# 中以编程方式访问它。

要远程访问它,你需要在 performance counter class constructor 中指定服务器名称,并将模拟的帐户添加到“性能监视器用户”组中:

net localgroup "Performance Monitor Users" %username% /add

如果提供查询该值的“PerformanceCounter”代码,将会非常有帮助,甚至是必要的。 - Lance U. Matthews

-1

如果您需要翻译,这里是 VB.NET 的等效代码。

        Dim path = New ManagementPath With {.NamespacePath = "root\cimv2",
                                          .Server = "<REMOTE HOST OR IP>"}
    Dim scope = New ManagementScope(path)
    Dim condition = "DriveLetter = 'C:'"
    Dim selectedProperties = {"FreeSpace"}
    Dim query = New SelectQuery("Win32_Volume", condition, selectedProperties)
    Dim searcher = New ManagementObjectSearcher(scope, query)
    Dim results = searcher.Get()
    Dim volume = results.Cast(Of ManagementObject).SingleOrDefault()
    If volume IsNot Nothing Then
        Dim freeSpace As ULong = volume.GetPropertyValue("FreeSpace")

    End If

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接