如何确定远程驱动器是否有足够的空间使用C#写入文件?

时间:2021-08-22 13:24:10

How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?

如何确定远程驱动器是否有足够的空间让我在.Net中使用C#上传给定文件?

4 个解决方案

#1


10  

There are two possible solutions.

有两种可能的解决方案。

  1. Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program:

    调用Win32函数GetDiskFreeSpaceEx。这是一个示例程序:

    internal static class Win32
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
    
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            long freeBytesForUser;
            long totalBytes;
            long freeBytes;
    
            if (Win32.GetDiskFreeSpaceEx(@"\\prime\cargohold", out freeBytesForUser, out totalBytes, out freeBytes)) {
                Console.WriteLine(freeBytesForUser);
                Console.WriteLine(totalBytes);
                Console.WriteLine(freeBytes);
            }
        }
    }
    
  2. Use the system management interface. There is another answer in this post which describes this. This method is really designed for use in scripting languages such as PowerShell. It performs a lot of fluff just to get the right object. Ultimately, I suspect, this method boils down to calling GetDiskFreeSpaceEx.

    使用系统管理界面。这篇文章中有另一个答案描述了这一点。此方法实际上设计用于脚本语言,如PowerShell。它只是为了获得正确的物体而执行大量的绒毛。最后,我怀疑,这种方法归结为调用GetDiskFreeSpaceEx。

Anybody doing any serious Windows development in C# will probably end up calling many Win32 functions. The .NET framework just doesn't cover 100% of the Win32 API. Any large program will quickly uncover gaps in the .NET libraries that are only available through the Win32 API. I would get hold of one of the Win32 wrappers for .NET and include this in your project. This will give you instant access to just about every Win32 API.

任何在C#中进行任何严肃的Windows开发的人都可能会最终调用许多Win32函数。 .NET框架不能覆盖100%的Win32 API。任何大型程序都可以快速发现.NET库中只能通过Win32 API获得的空白。我会得到一个.NET的Win32包装器,并将其包含在您的项目中。这将使您可以即时访问几乎所有Win32 API。

#2


5  

Use WMI

using System.Management;

// Get all the network drives (drivetype=4)
SelectQuery query = new SelectQuery("select Name, VolumeName, FreeSpace from win32_logicaldisk where drivetype=4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject drive in searcher.Get())
{
    string Name = (string)drive["Name"];
    string VolumeName = (string)drive["VolumeName"];
    UInt64 freeSpace = (UInt64)drive["FreeSpace"];
}

based on (stolen from) http://www.dreamincode.net/code/snippet1576.htm

基于(被盗)http://www.dreamincode.net/code/snippet1576.htm

#3


2  

Are you talking about mapping a network share to a logical drive on you computer?

您是在谈论将网络共享映射到计算机上的逻辑驱动器吗?

If so you can use DriveInfo.

如果是这样,您可以使用DriveInfo。

    DriveInfo info = new DriveInfo("X:");

    info.AvailableFreeSpace;

DriveInfo only works with logical drives so if you are just using the full share (UNC) name I don't think the above code will work.

DriveInfo仅适用于逻辑驱动器,因此如果您只使用完整共享(UNC)名称,我认为上述代码不起作用。

#4


2  

I'm not sure if GetDiskFreeSpaceEx works on UNC shares, but if it does use that, otherwise here is how to mount a UNC share to a logal drive:

我不确定GetDiskFreeSpaceEx是否适用于UNC共享,但是如果它确实使用它,否则这里是如何将UNC共享安装到logal驱动器:

EDIT GetDiskFreeSpaceEx does work on UNC shares, use that...however, this code was too much effort to just delete, and is handy if you ever want to mount a UNC share as a local drive in your code.

编辑GetDiskFreeSpaceEx确实可以处理UNC共享,使用它......但是,这段代码只需要删除就太费力了,如果您想在代码中将UNC共享作为本地驱动器挂载,则非常方便。

public class DriveWrapper
{                    
    [StructLayout(LayoutKind.Sequential)]
    public struct NETRESOURCEA
    {
        public int dwScope;
        public int dwType;
        public int dwDisplayType;
        public int dwUsage;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpLocalName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpRemoteName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpComment;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpProvider;
        public override String ToString()
        {
            String str = "LocalName: " + lpLocalName + " RemoteName: " + lpRemoteName
                  + " Comment: " + lpComment + " lpProvider: " + lpProvider;
            return (str);
        }
    }

    [DllImport("mpr.dll")]
    public static extern int WNetAddConnection2A(
          [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,
          [MarshalAs(UnmanagedType.LPStr)] string lpPassword,
          [MarshalAs(UnmanagedType.LPStr)] string UserName,
          int dwFlags);       
    [DllImport("mpr.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern int WNetCancelConnection2A(
          [MarshalAs(UnmanagedType.LPStr)]
        string lpName,
          int dwFlags,
          int fForce
          );

    public int GetDriveSpace(string shareName, string userName, string password)
    {
        NETRESOURCEA[] n = new NETRESOURCEA[1];
        n[0] = new NETRESOURCEA();

        n[0].dwScope = 0;
        n[0].dwType = 0;
        n[0].dwDisplayType = 0;
        n[0].dwUsage = 0;

        n[0].dwType = 1;

        n[0].lpLocalName = "x:";
        n[0].lpRemoteName = shareName;
        n[0].lpProvider = null;

        int res = WNetAddConnection2A(n, userName, password, 1);

        DriveInfo info = new DriveInfo("x:");
        int space = info.AvailableFreeSpace;

        int err = 0;
        err = WNetCancelConnection2A("x:", 0, 1);

        return space;
    }
}

#1


10  

There are two possible solutions.

有两种可能的解决方案。

  1. Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program:

    调用Win32函数GetDiskFreeSpaceEx。这是一个示例程序:

    internal static class Win32
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
    
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            long freeBytesForUser;
            long totalBytes;
            long freeBytes;
    
            if (Win32.GetDiskFreeSpaceEx(@"\\prime\cargohold", out freeBytesForUser, out totalBytes, out freeBytes)) {
                Console.WriteLine(freeBytesForUser);
                Console.WriteLine(totalBytes);
                Console.WriteLine(freeBytes);
            }
        }
    }
    
  2. Use the system management interface. There is another answer in this post which describes this. This method is really designed for use in scripting languages such as PowerShell. It performs a lot of fluff just to get the right object. Ultimately, I suspect, this method boils down to calling GetDiskFreeSpaceEx.

    使用系统管理界面。这篇文章中有另一个答案描述了这一点。此方法实际上设计用于脚本语言,如PowerShell。它只是为了获得正确的物体而执行大量的绒毛。最后,我怀疑,这种方法归结为调用GetDiskFreeSpaceEx。

Anybody doing any serious Windows development in C# will probably end up calling many Win32 functions. The .NET framework just doesn't cover 100% of the Win32 API. Any large program will quickly uncover gaps in the .NET libraries that are only available through the Win32 API. I would get hold of one of the Win32 wrappers for .NET and include this in your project. This will give you instant access to just about every Win32 API.

任何在C#中进行任何严肃的Windows开发的人都可能会最终调用许多Win32函数。 .NET框架不能覆盖100%的Win32 API。任何大型程序都可以快速发现.NET库中只能通过Win32 API获得的空白。我会得到一个.NET的Win32包装器,并将其包含在您的项目中。这将使您可以即时访问几乎所有Win32 API。

#2


5  

Use WMI

using System.Management;

// Get all the network drives (drivetype=4)
SelectQuery query = new SelectQuery("select Name, VolumeName, FreeSpace from win32_logicaldisk where drivetype=4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject drive in searcher.Get())
{
    string Name = (string)drive["Name"];
    string VolumeName = (string)drive["VolumeName"];
    UInt64 freeSpace = (UInt64)drive["FreeSpace"];
}

based on (stolen from) http://www.dreamincode.net/code/snippet1576.htm

基于(被盗)http://www.dreamincode.net/code/snippet1576.htm

#3


2  

Are you talking about mapping a network share to a logical drive on you computer?

您是在谈论将网络共享映射到计算机上的逻辑驱动器吗?

If so you can use DriveInfo.

如果是这样,您可以使用DriveInfo。

    DriveInfo info = new DriveInfo("X:");

    info.AvailableFreeSpace;

DriveInfo only works with logical drives so if you are just using the full share (UNC) name I don't think the above code will work.

DriveInfo仅适用于逻辑驱动器,因此如果您只使用完整共享(UNC)名称,我认为上述代码不起作用。

#4


2  

I'm not sure if GetDiskFreeSpaceEx works on UNC shares, but if it does use that, otherwise here is how to mount a UNC share to a logal drive:

我不确定GetDiskFreeSpaceEx是否适用于UNC共享,但是如果它确实使用它,否则这里是如何将UNC共享安装到logal驱动器:

EDIT GetDiskFreeSpaceEx does work on UNC shares, use that...however, this code was too much effort to just delete, and is handy if you ever want to mount a UNC share as a local drive in your code.

编辑GetDiskFreeSpaceEx确实可以处理UNC共享,使用它......但是,这段代码只需要删除就太费力了,如果您想在代码中将UNC共享作为本地驱动器挂载,则非常方便。

public class DriveWrapper
{                    
    [StructLayout(LayoutKind.Sequential)]
    public struct NETRESOURCEA
    {
        public int dwScope;
        public int dwType;
        public int dwDisplayType;
        public int dwUsage;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpLocalName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpRemoteName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpComment;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpProvider;
        public override String ToString()
        {
            String str = "LocalName: " + lpLocalName + " RemoteName: " + lpRemoteName
                  + " Comment: " + lpComment + " lpProvider: " + lpProvider;
            return (str);
        }
    }

    [DllImport("mpr.dll")]
    public static extern int WNetAddConnection2A(
          [MarshalAs(UnmanagedType.LPArray)] NETRESOURCEA[] lpNetResource,
          [MarshalAs(UnmanagedType.LPStr)] string lpPassword,
          [MarshalAs(UnmanagedType.LPStr)] string UserName,
          int dwFlags);       
    [DllImport("mpr.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern int WNetCancelConnection2A(
          [MarshalAs(UnmanagedType.LPStr)]
        string lpName,
          int dwFlags,
          int fForce
          );

    public int GetDriveSpace(string shareName, string userName, string password)
    {
        NETRESOURCEA[] n = new NETRESOURCEA[1];
        n[0] = new NETRESOURCEA();

        n[0].dwScope = 0;
        n[0].dwType = 0;
        n[0].dwDisplayType = 0;
        n[0].dwUsage = 0;

        n[0].dwType = 1;

        n[0].lpLocalName = "x:";
        n[0].lpRemoteName = shareName;
        n[0].lpProvider = null;

        int res = WNetAddConnection2A(n, userName, password, 1);

        DriveInfo info = new DriveInfo("x:");
        int space = info.AvailableFreeSpace;

        int err = 0;
        err = WNetCancelConnection2A("x:", 0, 1);

        return space;
    }
}