我试图从长文件名中获取短文件名,但我在 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/