私は失敗したDLLIMPORTをどのように扱うのですか?
-
13-09-2019 - |
質問
予想通り、私は、C#のSHGetKnownFolderPathをラップするマネージクラスを書き込もうとしています今のところそれはVista上で動作しますが、原因shell32.dllの中に適切な機能を見つけることではないとXPにクラッシュします。
私はそれはので、私はXPを使用している場合System.Environment.GetFolderPathを使用して(確かハック)ソリューションにフォールバックすることができます設定したいです。 (または、より良い、それはShell32は中funcitonを見つけることができない場合。)
この他の条件付きコンパイルを実行する方法はありますか?
私の現在のコードは次のようになります:
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
}
所属していません StackOverflow