我正试图编写一个c托管类来包装shgetknownfolderpath,目前它在vista上工作,但在xp上由于在shell32.dll中找不到预期的正确函数而崩溃。
我想设置它,这样如果使用xp,我就可以使用system.environment.getfolderpath来回退到一个(无可否认是黑客)解决方案上。(或者,更好的是,如果它在shell32中找不到功能的话。)
除了条件编译,还有别的方法吗?
我当前的代码如下:
public abstract class KnownFolders
{
[DllImport("shell32.dll")]
private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
// Trim properties to get various Guids.
public static string GetKnownFolderPath(Guid guid)
{
IntPtr pPath;
int result = SHGetKnownFolderPath(guid, 0, IntPtr.Zero, out pPath);
if (result == 0)
{
string s = Marshal.PtrToStringUni(pPath);
Marshal.FreeCoTaskMem(pPath);
return s;
}
else
throw new System.ComponentModel.Win32Exception(result);
}
}
最佳答案
在try catch块中结束对shgetknownfolderpath的调用。捕获System.EntryPointNotFoundException,然后尝试其他解决方案:
public static string GetKnownFolderPath(Guid guid)
{
try
{
IntPtr pPath;
int result = SHGetKnownFolderPath(guid, 0, IntPtr.Zero, out pPath);
if (result == 0)
{
string s = Marshal.PtrToStringUni(pPath);
Marshal.FreeCoTaskMem(pPath);
return s;
}
else
throw new System.ComponentModel.Win32Exception(result);
}
catch(EntryPointNotFoundException ex)
{
DoAlternativeSolution();
}
}