Access to the path … is denied

久未见 提交于 2019-12-05 09:09:10

The only way to solve this problem is to not write to that folder. You are not allowed to write to that folder by convention, unfortunately, older versions of Windows did not hold you to this.

Instead, you can use Environment.SpecialFolder to help you find where you need to go:

// your application data for just that User running the app
var perUserAppData = Environment.GetFolderPath(
    Environment.SpecialFolder.ApplicationData);

// your application data for ALL users running the app
var allUsersAppData = Environment.GetFolderPath(
    Environment.SpecialFolder.CommonApplicationData);

// better!
var path = Path.Combine(perUserAppData, @"MyApp\MyFile.txt");

Basically, Windows 7 is telling you that you're going to have to stop driving on the sidewalks and use the street as was intended.

Move your file out of Program Files directory. In Win7 is readonly for normal users.

You could move the file in the ProgramData directory.
Your installer should create a directory for your application there.
Then inside your code you could retrieve the correct full pathname using these lines of code

string dataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
string appFile = Path.Combine(dataPath, "MyAppDir", "MyFile.txt");

usually (on Win7) this result in a path like this

c:\programdata\MyAppDir\MyFile.txt

but using the SpecialFolder enum you are guaranteed to use a folder available in readwrite to your application not depending on the current operating system.

As a short-term fix, you can use ICACLS to grant write access to the file. Note: NOT the whole directory.

As a longer term fix, you should NOT write to the program directory if you are running as unprivileged users, but instead somewhere like %LOCALAPPDATA% or %APPDATA%.

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