Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get free disk space

Tags:

c#

diskspace

Given each of the inputs below, I'd like to get free space on that location. Something like

long GetFreeSpace(string path) 

Inputs:

c:  c:\  c:\temp  \\server  \\server\C\storage 
like image 247
bh213 Avatar asked Sep 08 '09 12:09

bh213


2 Answers

this works for me...

using System.IO;  private long GetTotalFreeSpace(string driveName) {     foreach (DriveInfo drive in DriveInfo.GetDrives())     {         if (drive.IsReady && drive.Name == driveName)         {             return drive.TotalFreeSpace;         }     }     return -1; } 

good luck!

like image 89
erez dan Avatar answered Sep 27 '22 20:09

erez dan


Working code snippet using GetDiskFreeSpaceEx from link by RichardOD.

// Pinvoke for API function [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);  public static bool DriveFreeBytes(string folderName, out ulong freespace) {     freespace = 0;     if (string.IsNullOrEmpty(folderName))     {         throw new ArgumentNullException("folderName");     }      if (!folderName.EndsWith("\\"))     {         folderName += '\\';     }      ulong free = 0, dummy1 = 0, dummy2 = 0;      if (GetDiskFreeSpaceEx(folderName, out free, out dummy1, out dummy2))     {         freespace = free;         return true;     }     else     {         return false;     } } 
like image 35
sasha_gud Avatar answered Sep 27 '22 20:09

sasha_gud