Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 244
MrDatabase Avatar asked Sep 26 '08 01:09

MrDatabase


2 Answers

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

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.

like image 151
Mike Thompson Avatar answered Sep 28 '22 08:09

Mike Thompson


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

like image 42
s d Avatar answered Sep 28 '22 08:09

s d