c# - GetShortPathNameA 在 C# 中不起作用

标签 c# .net windows vb.net winapi

我试图从长文件名中获取短文件名,但我在 C# 代码中遇到了问题。 VB.Net 代码是:

Declare Function GetShortPathName Lib "kernel32" _
    Alias "GetShortPathNameA" (ByVal lpszLongPath As String, _
    ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long

Public Function GetShortName(ByVal sLongFileName As String) As String
    Dim lRetVal As Long, sShortPathName As String, iLen As Integer
    'Set up buffer area for API function call return
    sShortPathName = Space(255)
    iLen = Len(sShortPathName)

    'Call the function
    lRetVal = GetShortPathName(sLongFileName, sShortPathName, iLen)
    'Strip away unwanted characters.
     GetShortName = Left(sShortPathName, lRetVal)
End Function

我已将此函数转换为 C#:

[DllImport("kernel32", EntryPoint = "GetShortPathNameA")]
static extern long GetShortPathName(string lpszLongPath, string lpszShortPath, long cchBuffer);

public string GetShortName(string sLongFileName)
{
    long lRetVal;
    string sShortPathName;
    int iLen;

    // Set up buffer area for API function call return
    sShortPathName = new String(' ', 1024);
    iLen = sShortPathName.Length;

    // Call the function
    lRetVal = GetShortPathName(sLongFileName, sShortPathName, iLen);

    // Strip away unwanted characters.
    return sShortPathName.Trim();
}

但我无法让 c# 版本工作。我是不是遗漏了什么或出了什么问题?

最佳答案

VB 声明可以追溯到VB6,它非常不适合.NET 语言。尽管 P/Invoke 编码器允许将非托管代码写入字符串,但它会由于字符串驻留而导致随机失败。您也真的想要使用 Unicode 版本,这样您就不会得到意外的字符转换。如果函数失败,您想做一些有意义的事情。这是我的版本:

public static string GetShortName(string sLongFileName) {
  var buffer = new StringBuilder(259);
  int len = GetShortPathName(sLongFileName, buffer, buffer.Capacity);
  if (len == 0) throw new System.ComponentModel.Win32Exception();
  return buffer.ToString();
}

[DllImport("kernel32", EntryPoint = "GetShortPathName", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetShortPathName(string longPath, StringBuilder shortPath, int bufSize);

关于c# - GetShortPathNameA 在 C# 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2585171/

相关文章:

c# - 使用反射发现派生类型

c# - 将一些工作移至后台线程的最简单方法是什么?

c# - DrawUserIndexedPrimitives : Why do the indices have to be short instead of int?

c# - 如何随机选择一个字符串

c# - 在 .NET 中禁用 ChromeDriver 扩展

c# - 调用涉及由 WinForm 表单托管的 WPF 控件的调用永远不会返回

c# - 将值传递给 ObjectParameter 变量

c# - 如何在 Windows 应用程序中按名称动态创建 ToolStripMenuItem?

windows - 批处理文件 - 检查命令是否可用

windows - 如何通过 Windows 批处理操作递归替换名称