Access to the path .... is denied
Solution 1
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.
Solution 2
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.
s.k.paul
Updated on June 09, 2022Comments
-
s.k.paul almost 2 years
I have created a .msi by using VS2008 setup project. My application frequently writes some value in a .txt file in the application directory (C:\Program Files\MyApp\MyFile.txt). After insalling it in Win7, it raises an exception "Access to the path .... is denied."
But whenever I run it as administrator, no such exception occurs. Here is my sscce
string FilePath=Application.StartupPath + @"\AppSettings\CurrentUserName.inf"; using (StreamWriter writer=new StreamWriter(FilePath,false)) { writer.Write(txtLoginName.Text.Trim()); } MainForm.ProcessLogIn(); this.DialogResult = DialogResult.OK;
I don't know how to solve this problem. Any suggestion?
-
pylover over 11 yearsmanually check the file's permission, and ensure the current user has write access to the file.if not set proper permission when you creating the file.
-
Artemix over 11 yearsYou don't need to include signature in your post - your user card is added automatically. Read FAQ for more details.
-
s.k.paul over 11 years@ Artemix, I would not put my signature in future. sorry.
-
-
s.k.paul over 11 yearsThank you for your nice cooperation. But here is a little problem- Path.Combine() does not take 3 arguments. It should be var path = Path.Combine(perUserAppData, "MyApp\\MyFile.txt");
-
Sam over 11 yearsIt certainly does, perhaps just not with your version of .Net.