我正在设法从.NET应用程序中确定任意文件夹中的总磁盘空间和可用磁盘空间。通过文件夹中的“总磁盘空间”和“可用磁盘空间”,我指的是如果在文件夹上执行"dir“命令,该文件夹将报告的总磁盘空间和可用磁盘空间,即包含该文件夹的逻辑驱动器的总磁盘空间和可用磁盘空间,考虑到提出请求的用户帐户。
我正在使用C#。该方法应该同时适用于作为UNC路径的本地和远程文件夹(而不是通过映射的驱动器字母进行访问)。例如,它应适用于:
我从一个DirectoryInfo对象开始,但这似乎没有关联的磁盘空间信息。DriveInfo类可以,但是它不能处理远程文件夹。
编辑.与你们进行了一些交流,我正在考虑将远程文件夹映射为本地驱动器,使用DriveInfo获取数据,然后再取消映射。这种方法的问题是,我的应用程序需要每天收集120多个文件夹的数据。我不知道这是否可行。
有什么想法吗?谢谢。
发布于 2009-11-25 21:18:56
使用此链接来自MSDN类的System.IO.DriveInfo怎么样?
发布于 2009-11-25 21:43:32
这可能不是你想要的,但我试图帮助,它有一个额外的好处就是稍微安全地擦除你的驱动器的自由空间。
public static string DriveSizeAvailable(string path)
{
long count = 0;
byte toWrite = 1;
try
{
using (StreamWriter writer = new StreamWriter(path))
{
while (true)
{
writer.Write(toWrite);
count++;
}
}
}
catch (IOException)
{
}
return string.Format("There used to be {0} bytes available on drive {1}.", count, path);
}
public static string DriveSizeTotal(string path)
{
DeleteAllFiles(path);
int sizeAvailable = GetAvailableSize(path);
return string.Format("Drive {0} will hold a total of {1} bytes.", path, sizeAvailable);
}发布于 2015-08-11 21:47:41
这实际上不是一个C#示例,但可能会给您一个提示--一个VB.NET函数,返回指定路径上驱动器(以字节计)上的空闲空间和总空间。与System.IO.DriveInfo不同,它也适用于UNC路径。
VB.NET:
<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetDiskFreeSpaceEx(lpDirectoryName As String, ByRef lpFreeBytesAvailable As ULong, ByRef lpTotalNumberOfBytes As ULong, ByRef lpTotalNumberOfFreeBytes As ULong) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Public Shared Function GetDriveSpace(folderName As String, ByRef freespace As ULong, ByRef totalspace As ULong) As Boolean
If Not String.IsNullOrEmpty(folderName) Then
If Not folderName.EndsWith("\") Then
folderName += "\"
End If
Dim free As ULong = 0, total As ULong = 0, dummy2 As ULong = 0
If GetDiskFreeSpaceEx(folderName, free, total, dummy2) Then
freespace = free
totalspace = total
Return True
End If
End If
End Functionhttps://stackoverflow.com/questions/1799984
复制相似问题