如何处理失败的DllImport?

我正在尝试编写一个C#托管类来包装SHGetKnownFolderPath,到目前为止它可以在Vista上运行,但由于没有像预期的那样在shell32.dll中找到正确的函数而在XP上崩溃。

我想让它设置好所以如果使用XP,我可以使用System.Environment.GetFolderPath来回避(通常是hacky)解决方案。 (或者,更好的是,如果它在shell32中找不到function。)

除了条件编译之外,还有什么方法可以做到吗?

我目前的代码如下:

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(); } } 

您可以使用Environment.OSVersion属性检查操作系统版本。 我相信如果你这样做

 int osVersion = Environment.OSVersion.Version.Major 

在XP上将是5,在Vista上将是6.所以从那里只是一个简单的检查。

 if(osVersion == 5) { //do XP way } else if(osVersion == 6) { //P/Invoke it }