c# - 如何处理失败的 DllImport?

标签 c# windows-vista interop windows-xp dllimport

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

我想对其进行设置,以便在使用 XP 时可以使用 System.Environment.GetFolderPath 回退到一个(公认的 hacky)解决方案。 (或者,如果它在 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 block 中包装对 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();
  }
}

关于c# - 如何处理失败的 DllImport?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/970017/

相关文章:

c# - 同步生产和测试数据库的方法

windows-vista - 如何确定机器退出暂停的原因?

c# - P/Invoke 语法 - 我是否在 C# 中正确翻译了我的 C++ 函数?

java - 如何从 JSP 页面加载 COM 对象?

C# Interop - 释放在非托管代码中分配的内存

c# - 为什么这个泛型方法要求 T 有一个公共(public)的、无参数的构造函数?

c# - Linq to XML - 使用 linq query.n 时出现空引用异常

winapi - 适用于VISTA,7及更高版本的Windows API

c# - 动态类型传递和实例化——如何?

svn - TortoiseSVN 在 Windows Vista 上不断导致资源管理器崩溃