[英]C# Error creating directory in SpecialFolder.LocalApplicationData on Windows 7 as a non Admin
I'm getting the error "Access to the path 'LocalApplicationData\\MyProgram\\' is denied." 我收到错误“访问路径'LocalApplicationData \\ MyProgram \\'被拒绝。” when trying to create a directory for my log file. 尝试为我的日志文件创建目录时。 This is when I'm running the program as a non-admin user. 这是我以非管理员用户身份运行程序的时候。
Directory.CreateDirectory(System.Environment.SpecialFolder.LocalApplicationData + "\\MyProgram\\");
Why would this be? 为什么会这样?
Thanks 谢谢
LocalApplicationData
is just an enum value. LocalApplicationData
只是一个枚举值。 You will have to use it in combination with GetFolderPath
: 您必须将它与GetFolderPath
结合使用:
string folder = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"MyProgram");
You're trying to access the enumeration value LocalApplicationData
as if it were a string. 您正在尝试访问枚举值LocalApplicationData
,就好像它是一个字符串。 It's not. 不是。 You need to find the folder path with GetFolderPath
: 您需要使用GetFolderPath
找到文件夹路径:
string path = Environment.GetFolderPath(
System.Environment.SpecialFolder.LocalApplicationData);
Incidentally, it's better form, and less error-prone, to use Path.Combine
to build up paths, rather than doing it by hand: 顺便说一句,使用Path.Combine
来构建路径,而不是手工完成,形式更好,更不容易出错:
string path = Path.Combine(@"C:\", "dir"); // gives you "C:\dir"
...and so your code would end up looking like: ...所以你的代码最终看起来像:
string appDataPath = Environment.GetFolderPath
(System.Environment.SpecialFolder.LocalApplicationData);
string path = Path.Combine(appDataPath, "MyProgram");
Directory.CreateDirectory(path);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.