How to call the Win32 GetCurrentDirectory function from C#?

The prototype of GetCurrentDirectory

DWORD GetCurrentDirectory(
  [in]  DWORD  nBufferLength,
  [out] LPTSTR lpBuffer
);

DWORD is unsigned long, LPTSTR is a pointer to wchar buffer in Unicode environment. It can be called from C++

#define MAX_BUFFER_LENGTH 256

int main() {
  TCHAR buffer[MAX_BUFFER_LENGTH];
  GetCurrentDirectory(MAX_BUFFER_LENGTH, buffer);
  return 0;
}

I tried to encapsulate this win32 function in C#, but failed.

[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern uint GetCurrentDirectory(uint nBufferLength, out StringBuilder lpBuffer);

>Solution :

You simply need to remove out on the StringBuilder parameter:

[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern uint GetCurrentDirectory(uint nBufferLength, StringBuilder lpBuffer);

And then pre-allocate the buffer when calling the function:

var buffer = new StringBuilder(MAX_BUFFER_LENGTH); 
GetCurrentDirectory(buffer.Capacity, buffer);
var path = buffer.ToString();

That being said, you can just use Directory.GetCurrentDirectory() instead:

var path = Directory.GetCurrentDirectory();

Leave a Reply