Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to the path .... is denied

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?

like image 279
s.k.paul Avatar asked Dec 18 '12 14:12

s.k.paul


1 Answers

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.

like image 101
Steve Avatar answered Oct 03 '22 16:10

Steve