Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get available disk free space for a given path on Windows [duplicate]

Tags:

c#

windows

Possible Duplicate:
Programmatically determining space available from UNC Path

I'm trying to find a function that I can call from C# to retrieve that information. This is what I have tried so far:

String folder = "z:\myfolder"; // It works
folder = "\\mycomputer\myfolder"; // It doesn't work

System.IO.DriveInfo drive = new System.IO.DriveInfo(folder);
System.IO.DriveInfo a = new System.IO.DriveInfo(drive.Name);
long HDPercentageUsed = 100 - (100 * a.AvailableFreeSpace / a.TotalSize);

This works ok, but only if I pass a drive letter. Is there a way of retrieving the free space by passing a whole path?

like image 856
LEM Avatar asked Jan 22 '13 18:01

LEM


People also ask

How do I check disk space availability?

To check the total disk space left on your Windows 10 device, select File Explorer from the taskbar, and then select This PC on the left. The available space on your drive will appear under Devices and drives.

How do I fix free disk space?

One of the easiest ways to clean up files you no longer need is by using Disk Cleanup. Open Disk Cleanup by clicking the Start button . In the search box, type Disk Cleanup, and then, in the list of results, select Disk Cleanup. If prompted, select the drive that you want to clean up, and then select OK.


1 Answers

Try to use the winapi function GetDiskFreeSpaceEx:

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
   out ulong lpFreeBytesAvailable,
   out ulong lpTotalNumberOfBytes,
   out ulong lpTotalNumberOfFreeBytes);

ulong FreeBytesAvailable;
ulong TotalNumberOfBytes;
ulong TotalNumberOfFreeBytes;

bool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder",
                                  out FreeBytesAvailable,
                                  out TotalNumberOfBytes,
                                  out TotalNumberOfFreeBytes);
if(!success)
    throw new System.ComponentModel.Win32Exception();

Console.WriteLine("Free Bytes Available:      {0,15:D}", FreeBytesAvailable);
Console.WriteLine("Total Number Of Bytes:     {0,15:D}", TotalNumberOfBytes);
Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);
like image 142
rekire Avatar answered Nov 01 '22 19:11

rekire