C# 在 Windows 上获取给定路径的可用磁盘可用空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14465187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:53:52  来源:igfitidea点击:

Get available disk free space for a given path on Windows

c#windows

提问by LEM

Possible Duplicate:
Programmatically determining space available from UNC Path

可能的重复:以
编程方式确定 UNC 路径中的可用空间

I'm trying to find a function that I can call from C# to retrieve that information. This is what I have tried so far:

我试图找到一个可以从 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);

This works ok, but only if I pass a drive letter. Is there a way of retrieving the free space by passing a whole path?

这工作正常,但前提是我传递了一个驱动器号。有没有办法通过整个路径来检索可用空间?

Thanks.

谢谢。

采纳答案by rekire

Try to use the winapi function GetDiskFreeSpaceEx:

尝试使用 winapi 函数GetDiskFreeSpaceEx

[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);