P/Invoke ?

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());
}
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
W

Willy Denoyette [MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top