P/Invoke ?

  • Thread starter Thread starter John Cantley
  • Start date Start date
J

John Cantley

Here is what I have, I am not getting back any values all are returned as
zero. But it seems to me that the call is not running at all. what am i
doing wrong or missing?

public class WinApi
{
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern bool GetDiskFreeSpaceEx(
[MarshalAs(UnmanagedType.LPTStr)] string lpDirectoryName,
[MarshalAs(UnmanagedType.U8)] long lpFreeBytesAvailable,
[MarshalAs(UnmanagedType.U8)] long lpTotalNumberOfBytes,
[MarshalAs(UnmanagedType.U8)] long lpTotalNumberOfFreeBytes);
}

protected void GetFreeSpace()
{
long lFreeBytes = 0;
long lTotBytes = 0;
long lTotFreeBytes = 0;
string sDir = "C:\\";
bool bOk = WinApi.GetDiskFreeSpaceEx(sDir, lFreeBytes, lTotBytes,
lTotFreeBytes);
if (bOk)
Console.Write(lFreeBytes.ToString());
}
 
John,

Import the System.ComponentModel namespace and then do this:

if (bOk)
Console.Write(lFreeBytes.ToString());
else
throw new Win32Exception();

This will throw an exception with the information why the call failed
(if it did).

Hope this helps.
 
John,

You should pass a "pointer to a long" for the out arguments in both, the declaration and the call.

[MarshalAs(UnmanagedType.U8)] ref long lpFreeBytesAvailable,
....

bool bOk = WinApi.GetDiskFreeSpaceEx(sDir, ref lFreeBytes, ref lTotBytes,
ref lTotFreeBytes);

Willy.
 
Back
Top