Mif*_*Fox 4 c# interop windows-xp dllimport windows-vista
我正在尝试编写一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
在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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3607 次 |
| 最近记录: |