Has*_*anG 2 .net c# vb.net windows 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
Run Code Online (Sandbox Code Playgroud)
我已将此函数转换为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();
}
Run Code Online (Sandbox Code Playgroud)
但我不能让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);
Run Code Online (Sandbox Code Playgroud)