获得可用磁盘的可用空间在Windows上给定路径

获得可用磁盘的可用空间在Windows上给定路径

本文介绍了获得可用磁盘的可用空间在Windows上给定路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果

我试图发现我可以从C#调用来检索信息的功能。
这是我到目前为止已经试过:

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:

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?

感谢。

推荐答案

尝试使用WINAPI函数:

Try to use the winapi function 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);

这篇关于获得可用磁盘的可用空间在Windows上给定路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:12