我正在尝试使用SHSetKnownFolderPath设置ProgramFiles的“已知文件夹路径”的路径。
以下是我在下面所做的事情但却引发了异常: System.ArgumentException:值不在预期范围内。
using System;
using System.Runtime.InteropServices;
namespace TestApplication {
class Program {
[Flags]
public enum KnownFolderFlag : uint {
None = 0x0,
CREATE = 0x8000,
DONT_VERFIY = 0x4000,
DONT_UNEXPAND = 0x2000,
NO_ALIAS = 0x1000,
INIT = 0x800,
DEFAULT_PATH = 0x400,
NOT_PARENT_RELATIVE = 0x200,
SIMPLE_IDLIST = 0x100,
ALIAS_ONLY = 0x80000000
}
[DllImport("shell32.dll")]
public static extern int SHGetKnownFolderPath(
[MarshalAs(UnmanagedType.LPStruct)] Guid rfid,
uint dwFlags,
IntPtr hToken,
out IntPtr pszPath // API uses CoTaskMemAlloc
);
[DllImport("shell32.dll")]
public static extern int SHSetKnownFolderPath(ref Guid guid, uint flags, IntPtr hToken, string newPath);
public static readonly Guid ProgramFiles = new Guid("905e63b6-c1bf-494e-b29c-65b732d3d21a");
public static readonly Guid ProgramFilesX64 = new Guid("6D809377-6AF0-444b-8957-A3773F02200E");
public static readonly Guid ProgramFilesX86 = new Guid("7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E");
static void Main(string[] args) {
Guid[] guids = new Guid[] {
ProgramFiles,
ProgramFilesX64,
ProgramFilesX86
};
// GET
foreach (Guid guid in guids) {
Console.WriteLine(string.Format("{0}; P/Invoke==>{1}", guid.ToString(), pinvokePath(guid)));
Console.WriteLine("");
}
// SET
Console.WriteLine("SET");
string thePath = @"C:\ProgramFiles_DCTEST";
int ret;
int flags = 0;
Guid progFiles = ProgramFiles;
ret = SHSetKnownFolderPath(ref progFiles, (uint)flags, IntPtr.Zero, thePath);
if (ret != 0) {
Console.WriteLine(ret);
Console.WriteLine(Marshal.GetExceptionForHR(ret));
}
// SET
Console.WriteLine("SET");
Guid progFilesX64 = ProgramFilesX64;
ret = SHSetKnownFolderPath(ref progFilesX64, (uint)flags, IntPtr.Zero, thePath);
if (ret != 0) {
Console.WriteLine(ret);
Console.WriteLine(Marshal.GetExceptionForHR(ret));
}
// SET
Console.WriteLine("SET");
Guid progFilesX86 = ProgramFilesX86;
ret = SHSetKnownFolderPath(ref progFilesX86, (uint)flags, IntPtr.Zero, thePath);
if (ret != 0) {
Console.WriteLine(ret);
Console.WriteLine(Marshal.GetExceptionForHR(ret));
}
// GET
foreach (Guid guid in guids) {
Console.WriteLine(string.Format("{0}; P/Invoke==>{1}", guid.ToString(), pinvokePath(guid)));
Console.WriteLine("");
}
Console.ReadLine();
}
private static string pinvokePath(Guid guid) {
IntPtr pPath;
SHGetKnownFolderPath(guid, 0, IntPtr.Zero, out pPath);
string path = System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath);
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pPath);
return path;
}
}
}
欢迎帮助!花了太长时间看这个......