Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

.net - How can I determine if a remote drive has enough space to write a file using C#?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two possible solutions.

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

    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(@"\primecargohold", 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...