找出 .NET 中的总磁盘空间和可用磁盘空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1799984/
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-09-03 13:35:42  来源:igfitidea点击:

Finding out total and free disk space in .NET

.netdirectorydiskspace

提问by CesarGon

I am trying to find a way to determine the total and available disk space in an arbitrary folder from a .NET app. By "total disk space" and "available disk space" in a folder I refer to the total and available disk space that this folder would report if you performed a "dir" command on it, that is, the total and available disk space of the logical drive containing that folder, considering the user account under which the request is being made.

我试图找到一种方法来确定 .NET 应用程序中任意文件夹中的总磁盘空间和可用磁盘空间。文件夹中的“总磁盘空间”和“可用磁盘空间”是指如果您对其执行“dir”命令,该文件夹将报告的总磁盘空间和可用磁盘空间,即总磁盘空间和可用磁盘空间包含该文件夹的逻辑驱动器,考虑到发出请求的用户帐户。

I am using C#. The method should work both for local and remote folders given as UNC paths (rather than accessed through mapped drive letters). For example, it should work for:

我正在使用 C#。该方法应该适用于作为 UNC 路径(而不是通过映射的驱动器号访问)的本地和远程文件夹。例如,它应该适用于:

  • C:\Temp
  • \\Silfen\Resources\Temp2
  • C:\温度
  • \\Silfen\Resources\Temp2

I am starting with a DirectoryInfo object, but this seems to have no associated disk space information. The DriveInfo class does, but it won't work with remote folders.

我从 DirectoryInfo 对象开始,但这似乎没有关联的磁盘空间信息。DriveInfo 类可以,但它不适用于远程文件夹。

Edit.After some exchanges with you guys, I am considering mapping remote folders as local drives, using DriveInfo to obtain the data, and unmapping again. The problem with this approach is that my app needs to collect the data for over 120 folders a few times a day, every day. I am not sure this would be feasible.

编辑。和大家交流了一下,考虑把远程文件夹映射成本地驱动,用DriveInfo去获取数据,再解映射。这种方法的问题在于,我的应用程序每天需要多次收集 120 多个文件夹的数据。我不确定这是否可行。

Any ideas? Thanks.

有任何想法吗?谢谢。

采纳答案by t0mm13b

How about this link from MSDNthat uses the System.IO.DriveInfoclass?

来自 MSDN 的使用System.IO.DriveInfo该类的链接怎么样?

回答by t0mm13b

You can use GetDiskFreeSpaceEx from kernel32.dllwhich works with UNC-paths and drives. All you need to do is include a DllImport (see link for an example).

您可以使用 kernel32.dll中的GetDiskFreeSpaceEx,它适用于 UNC 路径和驱动器。您需要做的就是包含一个 DllImport(有关示例,请参见链接)。

回答by Jeffrey L Whitledge

This maynot be what you want, but I'm trying to help, and it has the bonus of slightly secure erasing the free space of your drive.

可能不是您想要的,但我正在努力提供帮助,它具有稍微安全地擦除驱动器可用空间的好处。

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

回答by Maksim Sestic

Not really a C# example but may give you a hint - a VB.NET function returning both amount of free and total space on drive (in bytes) along specified path. Works for UNC paths as well, unlike System.IO.DriveInfo.

不是真正的 C# 示例,但可能会给您一个提示 - 一个 VB.NET 函数返回指定路径上驱动器上的可用空间量和总空间量(以字节为单位)。也适用于 UNC 路径,与 System.IO.DriveInfo 不同。

VB.NET:

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 Function

回答by Herbert

Maksim Sestic has given the best answer, as it works on both, local and UNC paths. I have changed his code a little for better error handling and included an example. Works for me like a charm.

Maksim Sestic 给出了最好的答案,因为它适用于本地和 UNC 路径。为了更好地处理错误,我对他的代码做了一些改动,并包含了一个例子。对我来说就像一个魅力。

You need to put

你需要把

Imports System.Runtime.InteropServices

into your code, to allow DllImport to be recognized.

进入您的代码,以允许识别 DllImport。

Here is the modified code:

这是修改后的代码:

<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

Dim free As ULong = 0
Dim total As ULong = 0
Dim dummy2 As ULong = 0

Try

    If Not String.IsNullOrEmpty(folderName) Then

         If Not folderName.EndsWith("\") Then
             folderName += "\"
         End If

         If GetDiskFreeSpaceEx(folderName, free, total, dummy2) Then
             freespace = free
             totalspace = total
             Return True
         End If

     End If

Catch
End Try

    Return False

End Function

Call it this way:

这样称呼它:

dim totalspace as ulong = 0
dim freespace as ulong = 0
if GetDriveSpace("\anycomputer\anyshare", freespace, totalspace) then
    'do what you need to do with freespace and totalspace
else
    'some error
end if

The foldername can also be a local directory like drive:\path\path\...

文件夹名也可以是本地目录,如 drive:\path\path\...

It is still in VB.NET but shouldn't be a problem to translate into C#.

它仍然在 VB.NET 中,但转换成 C# 应该不是问题。

回答by CrazyIvan1974

Here's one more possibility that I've used for years. The example below is VBScript, but it should work with any COM-aware language. Note that GetDrive()works on UNC shares as well.

这是我多年来使用的另一种可能性。下面的示例是 VBScript,但它应该适用于任何可识别 COM 的语言。请注意,这也GetDrive()适用于 UNC 共享。

Dim Tripped
Dim Level

Tripped = False
Level   = 0

Sub Read(Entry, Source, SearchText, Minimum, Maximum)

    Dim fso
    Dim disk

    Set fso  = CreateObject("Scripting.FileSystemObject")

    Set disk = fso.GetDrive(Source)

    Level = (disk.AvailableSpace / (1024 * 1024 * 1024))

    If (CDbl(Level) < CDbl(Minimum)) or (CDbl(Level) > CDbl(Maximum)) Then
        Tripped = True
    Else
        Tripped = False
    End If

End Sub

回答by Ken White

System.IO.DriveInfo works fine. I'm attached to two separate Netware servers, with several drives mapped.

System.IO.DriveInfo 工作正常。我连接到两个独立的 Netware 服务器,映射了几个驱动器。

Here's for the local C: drive:

这是本地 C: 驱动器:

Drive C:\
  File type: Fixed
  Volume label: Drive C
  File system: NTFS
  Available space to current user:   158558248960 bytes
  Total available space:             158558248960 bytes
  Total size of drive:               249884004352 bytes 

Here's the output for one of the network drives:

这是其中一个网络驱动器的输出:

Drive F:\
  File type: Network
  Volume label: SYS
  File system: NWFS
  Available space to current user:     1840656384 bytes
  Total available space:               1840656384 bytes
  Total size of drive:                 4124475392 bytes 

I used the following code, directly from the MSDN docs on DriveInfo:

我使用了以下代码,直接来自 DriveInfo 上的 MSDN 文档:

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

回答by Neil N

I'm pretty sure this is impossible. In windows explorer, if I try to get the folder properties of a UNC directory, it gives me nothing as far as available space. Used/Available space is a characteristic of drives, not folders, and UNC shares are treated as just folders.

我很确定这是不可能的。在 Windows 资源管理器中,如果我尝试获取 UNC 目录的文件夹属性,它不会给我任何可用空间。已用/可用空间是驱动器而非文件夹的特征,并且 UNC 共享仅被视为文件夹。

you have to either:
- Map a drive
- Run something on the remote machine to check disk space.

你必须:
- 映射驱动器
- 在远程机器上运行一些东西来检查磁盘空间。

You could also run into problems with something like Distributed file system, in which a UNC/Mapped share is NOT tied to any specific drive, so there youd have to actually sum up several drives.

您还可能遇到分布式文件系统之类的问题,其中 UNC/映射共享不绑定到任何特定驱动器,因此您实际上必须总结几个驱动器。

And what about user quotas? The drive may not be full, but the account you are using to write to that folder may have hit its limit.

那么用户配额呢?驱动器可能未满,但您用来写入该文件夹的帐户可能已达到其限制。

回答by Mike

Not C# and only gives the avilable space, but . . .

不是 C#,只提供可用空间,但是 . . .

dir \server\share | find /i "bytes free"

gets you part of the way. I'm looking or the same solution but there doesn't seem to be a nice one - especially when trying to avoid mapping drives.

让你成为其中的一部分。我正在寻找或相同的解决方案,但似乎没有一个好的解决方案 - 特别是在尝试避免映射驱动器时。