如何从 C# 调用 Win32 GetCurrentDirectory 函数?

How to call the Win32 GetCurrentDirectory function from C#?

GetCurrentDirectory

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

DWORDunsigned longLPTSTR是Unicode环境下wchar缓冲区的指针。它可以从 C++ 调用

#define MAX_BUFFER_LENGTH 256

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

我尝试用C#封装这个win32函数,但是失败了。

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

您只需删除 StringBuilder 参数上的 out

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

然后pre-allocate调用函数时的缓冲区:

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

也就是说,您可以只使用 System.IO.Directory.GetCurrentDirectory() 来代替:

var path = Directory.GetCurrentDirectory();