C# 获取Windows上给定路径的可用磁盘可用空间
可能重复:C# 获取Windows上给定路径的可用磁盘可用空间,c#,windows,C#,Windows,可能重复: 我试图找到一个可以从C#调用的函数来检索这些信息。 这就是我迄今为止所尝试的: String folder = "z:\myfolder"; // It works folder = "\\mycomputer\myfolder"; // It doesn't work System.IO.DriveInfo drive = new System.IO.DriveInfo(folder); System.IO.DriveInfo a = new System.IO.DriveIn
我试图找到一个可以从C#调用的函数来检索这些信息。 这就是我迄今为止所尝试的:
String folder = "z:\myfolder"; // It works
folder = "\\mycomputer\myfolder"; // It doesn't work
System.IO.DriveInfo drive = new System.IO.DriveInfo(folder);
System.IO.DriveInfo a = new System.IO.DriveInfo(drive.Name);
long HDPercentageUsed = 100 - (100 * a.AvailableFreeSpace / a.TotalSize);
这工作正常,但只有当我传递一个驱动器号时。有没有一种方法可以通过传递整个路径来检索空闲空间
谢谢。尝试使用winapi函数:
谢谢,这似乎奏效了!直到我无意中使用了“C:\\”
success=GetDiskFreeSpaceEx(“C:\\”,out FreeBytesAvailable,…
@J.Chris你错过了第一个引号前的@符号,这使得掩蔽变得过时。谢谢你@rekire!我实际上没有这个问题,因为我使用的是文件夹=@“C:\”;
并使用变量文件夹。我简化了代码,但忽略了“@”。我遇到的问题是试图使用像“\\L9F603\Home”这样的字符串,即计算机名(不是我的真实计算机名)斜杠驱动器或目录。如果有人能发布如何指定计算机名或特定目录,我想知道这一点(但这个项目不需要它)。有人知道在纯点网络中不需要API调用就可以做到这一点吗?DriveInfo似乎只适用于驱动器,而不适用于UNC路径。请看。Mitch Wheat回答:我相信您需要通过P/Invoke调用GetDiskFreeSpace(Win32 API)来获得UNC网络驱动器的磁盘可用空间。
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
ulong FreeBytesAvailable;
ulong TotalNumberOfBytes;
ulong TotalNumberOfFreeBytes;
bool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder",
out FreeBytesAvailable,
out TotalNumberOfBytes,
out TotalNumberOfFreeBytes);
if(!success)
throw new System.ComponentModel.Win32Exception();
Console.WriteLine("Free Bytes Available: {0,15:D}", FreeBytesAvailable);
Console.WriteLine("Total Number Of Bytes: {0,15:D}", TotalNumberOfBytes);
Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);