views:

187

answers:

3

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.

+4  A: 

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.

Noldorin
A: 

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

Stevo3000
A: 

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.

Guffa
I was thinking of making sure that that two to three times the spaces that is needed exists just to have extra coverage. But thanks for the note
Matthew Whited