我可以从这篇文章:使用c-net的远程桌面查看远程连接的pc。但我不需要它。我只要连上那台电脑,就能得到C盘的空闲空间数据。我怎么能这么做?我可以连接到远程桌面。我可以使用IO命名空间获得driveInfo。但是如何把它们结合起来呢?
使用System.Management
命名空间和Win32_Volume
WMI类。您可以查询具有DriveLetter
或C:
的实例,并检索其FreeSpace
属性,如下所示:
ManagementPath path = new ManagementPath() {
NamespacePath = @"rootcimv2",
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
属性用来存储卷的总大小
花了一整天的时间尝试让WMI远程工作但没有成功,我发现了使用性能计数器的替代方法。只需检查LogicalDisk
类别中的Free Megabytes
计数器,使用所需的驱动器号(以":"结尾)作为实例名,即可获得驱动器可用空闲空间的最新读数:
"LogicalDisk(C:)Free Megabytes"
你可以在c#中通过PerformanceCounter类编程地访问它。
要远程访问它,您需要向性能计数器类构造函数指定服务器名称,并且必须将模拟帐户添加到"性能监视器用户"中。组:
net localgroup "Performance Monitor Users" %username% /add
这里是vb.net等效的,以防您需要翻译它。
Dim path = New ManagementPath With {.NamespacePath = "rootcimv2",
.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