我想使用路径检查本地计算机中的可用磁盘空间... 这显示无效参数错误
string pathroot = "C:\Program Files (x86)\Personal\movies "
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"pathroot");
disk.Get();
string freespace = Convert.ToString(disk["FreeSpace"]);
return freespace;
谁能告诉我这是什么错误?或者还有其他方法吗?
答案 0 :(得分:3)
using System;
using System.IO;
class Test
{
public static void Main()
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" File type: {0}", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine(" Volume label: {0}", d.VolumeLabel);
Console.WriteLine(" File system: {0}", d.DriveFormat);
Console.WriteLine(
" Available space to current user:{0, 15} bytes",
d.AvailableFreeSpace);
Console.WriteLine(
" Total available space: {0, 15} bytes",
d.TotalFreeSpace);
Console.WriteLine(
" Total size of drive: {0, 15} bytes ",
d.TotalSize);
}
}
}
}
答案 1 :(得分:0)
字符串:
"win32_logicaldisk.deviceid=\"pathroot"
仅包含一个转义双引号。我不是专家,但我希望它是:
"win32_logicaldisk.deviceid=\"pathroot\""
但是,您实际上还没有将pathroot的值包含在生成的WMI查询中。为此,您可以使用以下内容:
var query = string.Format("win32_logicaldisk.deviceid=\"{0}\"", pathroot);
ManagementObject disk = new ManagementObject(query);
我还没有对它进行测试,但我认为这不起作用,因为“deviceid”需要一个“C:”形式的字符串而不是完整路径。从如下所示的完整路径获取驱动器号:
var driveLetter = System.IO.Path.GetPathRoot(pathroot);
var query = string.Format("win32_logicaldisk.deviceid=\"{0}\"", pathroot);
ManagementObject disk = new ManagementObject(query);
但请注意,当您需要能够查询UNC(网络共享)路径的驱动器空间时,此方法不起作用。
最后,带有路径的硬编码字符串不会被转义。例如,现在,\ Program Files中的\ P被视为转义序列,而不是文字\ P.用@标记字符串,使其变为:
string pathroot = @"C:\Program Files (x86)\Personal\movies"