Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading