How do I handle a failed DllImport?

后端 未结 2 521
攒了一身酷
攒了一身酷 2021-01-13 16:09

I\'m attempting to write a C# managed class to wrap SHGetKnownFolderPath, so far it works on Vista, but crashes on XP due to not finding the proper function in shell32.dll,

相关标签:
2条回答
  • 2021-01-13 16:35

    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
    }
    
    0 讨论(0)
  • 2021-01-13 16:37

    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();
      }
    }
    
    0 讨论(0)
提交回复
热议问题