yanpengl
yanpengl

Reputation: 260

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);

Upvotes: 0

Views: 228

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595412

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:

const int MAX_PATH = 260;
var buffer = new StringBuilder(MAX_PATH);
var len = GetCurrentDirectory(buffer.Capacity, buffer);
var path = buffer.ToString(0, len);

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

var path = Directory.GetCurrentDirectory();

Upvotes: 2

Related Questions