C# Error creating directory in SpecialFolder.LocalApplicationData on Windows 7 as a non Admin

為{幸葍}努か 提交于 2019-12-09 11:17:39

问题


I'm getting the error "Access to the path 'LocalApplicationData\MyProgram\' is denied." 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


回答1:


LocalApplicationData is just an enum value. You will have to use it in combination with GetFolderPath:

string folder = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.LocalApplicationData), 
    "MyProgram");



回答2:


You're trying to access the enumeration value LocalApplicationData as if it were a string. It's not. You need to find the folder path with 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:

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


来源:https://stackoverflow.com/questions/1992905/c-sharp-error-creating-directory-in-specialfolder-localapplicationdata-on-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!