Matthew Whited
Matthew Whited

Reputation: 22443

What is the best way to check file system capacity using .Net?

What is the best way in .Net to make sure a path as capacity to store a file. I need to makes sure I have room for the file before I download is becasue the source will not allow the file to be downloaded a second time. I have looked at System.IO.DriveInfo but this does not work for UNC paths.

Upvotes: 4

Views: 373

Answers (3)

Noldorin
Noldorin

Reputation: 147461

Here's a short function taken from this page that shows how you can get the free space of any drive (local or network/UNC) using WMI.

private static ulong GetFreeDiskSpaceInBytes(string drive)
{
    ManagementObject disk =
        new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + ":\"");
    disk.Get();
    return (ulong)disk["FreeSpace"];
}

If you wnat a Win32 API solution, you can use the GetDiskFreeSpaceEx function, as suggested by this MSDN help page. It too seems to support both local and network drive names.

Private Declare Function GetDiskFreeSpaceEx Lib "kernel32" _
    Alias "GetDiskFreeSpaceExA" (ByVal lpDirectoryName As String, _
    lpFreeBytesAvailableToCaller As Currency, _
    lpTotalNumberOfBytes As Currency, _
    lpTotalNumberOfFreeBytes As Currency) As Long

Private Sub Form_Click()
    Dim Status As Long
    Dim TotalBytes As Currency
    Dim FreeBytes As Currency
    Dim BytesAvailableToCaller As Currency

    Status = GetDiskFreeSpaceEx(Text1.Text, BytesAvailableToCaller, _
      TotalBytes, FreeBytes)
    If Status <> 0 Then
        MsgBox Format(TotalBytes * 10000, "#,##0"), , "Total Bytes"
        MsgBox Format(FreeBytes * 10000, "#,##0"), , "Free Bytes"
        MsgBox Format(BytesAvailableToCaller * 10000, "#,##0"), , _
          "Bytes Available To Caller"
    End If
End Sub

If you're having trouble converting that to C#, let me know.

I would have to recommend the WMI solution here, it being fully managed (aside from fewer lines), but either should do the trick.

Upvotes: 5

Guffa
Guffa

Reputation: 700780

The only sure way to see if the disk can store the file is to actually create a file of that size on the disk.

Even if the disk information says that there is room enough, due to defragmentation you can rarely use 100% of the free disk space.

Upvotes: 0

stevehipwell
stevehipwell

Reputation: 57558

I'm sure that you could get the answers you require using WMI, it is usually a good place to start.

Upvotes: 0

Related Questions