How do I handle a failed DllImport?

两盒软妹~` 提交于 2019-12-01 08:17:33
heavyd

Wrap your call to SHGetKnownFolderPath in a try-catch block. Catch the System.EntryPointNotFoundException and then try your alternative solution:

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

You can check the OS version using the Environment.OSVersion property. I believe if you do

int osVersion = Environment.OSVersion.Version.Major

on XP that will be 5, and on Vista that will be 6. So from there just to a simple check.

if(osVersion == 5)
{
   //do XP way
}
else if(osVersion == 6)
{
   //P/Invoke it
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!