下面是一些包裝函數LocalToUNC的C#代碼,它似乎工作正常,但我沒有廣泛地測試它。
[DllImport("mpr.dll")]
static extern int WNetGetUniversalNameA(
string lpLocalPath, int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize
);
// I think max length for UNC is actually 32,767
static string LocalToUNC(string localPath, int maxLen = 2000)
{
IntPtr lpBuff;
// Allocate the memory
try
{
lpBuff = Marshal.AllocHGlobal(maxLen);
}
catch (OutOfMemoryException)
{
return null;
}
try
{
int res = WNetGetUniversalNameA(localPath, 1, lpBuff, ref maxLen);
if (res != 0)
return null;
// lpbuff is a structure, whose first element is a pointer to the UNC name (just going to be lpBuff + sizeof(int))
return Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(lpBuff));
}
catch (Exception)
{
return null;
}
finally
{
Marshal.FreeHGlobal(lpBuff);
}
}
非常感謝這麼多 – 2010-08-30 05:47:31