【问题标题】:Getting drive info from a remote computer从远程计算机获取驱动器信息
【发布时间】:2013-01-04 18:18:24
【问题描述】:

我可以通过这篇文章查看远程连接的电脑:Remote Desktop using c-net。但我不需要它。我只需要连接那台电脑并获取 C 盘的可用空间数据。我怎么能这样做?我可以连接到远程桌面。我可以使用 IO 命名空间获取 driveInfo。但是如何结合它们呢?

【问题讨论】:

  • 如果您不需要远程桌面,为什么要使用远程桌面客户端?我建议为此查看 WMI - 请参阅 this question 了解如何。

标签: c# remote-desktop driveinfo


【解决方案1】:

为此使用System.Management namespaceWin32_Volume WMI class。您可以查询具有C:DriveLetter 的实例并检索其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 属性存储卷的总大小。

【讨论】:

  • 我不需要在路径中通过任何身份验证吗?
  • 这取决于您的环境。可以使用scope.Options property 设置凭据和其他安全选项,它是ConnectionOptions class 的一个实例。
  • 什么是freeSpace?是在 Bit 中吗?
  • 我发现它在字节中。但信息不准确。例如,C: 驱动器在服务器中有 56.5 GB 可用空间,但代码显示为 62GB。
  • @Si8 您从哪里获得“准确”的可用空间? Windows资源管理器?您是使用freeSpace / 1024 / 1024 / 1024 还是我想是freeSpace / 1000 / 1000 / 1000 来计算免费千兆字节?
【解决方案2】:

这是 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

【讨论】:

    【解决方案3】:

    在尝试让 WMI 远程工作但没有成功之后,我发现了使用性能计数器的替代方法。只需检查 LogicalDisk 类别中的 Free Megabytes 计数器,使用所需的驱动器号(附加“:”)作为实例名称,以获得驱动器可用空间的更新读数:

    "LogicalDisk(C:)\Free Megabytes"
    

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

    要远程访问它,您需要将服务器名称指定为performance counter class constructor,并且必须将模拟帐户添加到“Performance Monitor Users”组:

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

    【讨论】:

    • 如果没有必要,提供查询该值的PerformanceCounter 代码会很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多