2009-06-09 20 views
4

私はSHGetKnownFolderPathをラップするためにC#管理クラスを作成しようとしていますが、これまでのところVistaで動作しますが、期待通りにshell32.dllで適切な関数が見つからないためXPでクラッシュします。失敗したDllImportをどうすれば処理できますか?

XPを使用している場合は、System.Environment.GetFolderPathを使用して(確かにハッキーな)ソリューションにフォールバックすることができます。 (あるいは、shell32で関数を見つけることができない場合はさらに良いでしょう)

条件付きコンパイル以外の方法はありますか?

私の現在のコードは次のようになります。try-catchブロックでSHGetKnownFolderPathにお電話をラップ

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

答えて

9

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

これは機能しますが、1つの小さな変更があります。私はEntryPointNotFoundExceptionを捕まえなければならず、DllNotFoundExceptionを捕まえなければならなかった。関数がshell32.dllからのものであると見ると、機能的なWindowsプラットフォームでは欠けている可能性は低いです。 – MiffTheFox

+0

はい、それは正しいです、私は実際の例外を反映するために私の応答を更新します。 – heavyd

3

あなたはEnvironment.OSVersionプロパティを使用してOSのバージョンを確認することができます。私はあなたが5になりますXP上の、およびVista上

int osVersion = Environment.OSVersion.Version.Major 

をすればそこからちょうど簡単なチェックにそう6.だろうと信じています。

if(osVersion == 5) 
{ 
    //do XP way 
} 
else if(osVersion == 6) 
{ 
    //P/Invoke it 
} 
関連する問題