How can I create a file in C:\Program Files (x86)\myAplication on Windows7?

Apr 20 2010 4:08 PM
Hi.

I have a VS 2008 solution in which there are 2 projects.
One project is the actual application that outputs myApp.exe and the other project is a VS setup project linked to the first project.

The installer copies myApp.exe and the dependencies in C:\Program Files (x86)\appDir. In this same folder myApp.exe is trying, with no success, to create a new file.

The code in myApp looks something like this:
File.WriteAllLines(
Application.StartupPath + "myFile.txt",
new string[]{"test1", "test2", "test3"});
On Windows XP this works just fine.

On Windows 7 I get a System.UnauthorizedAccessException that reads: "Attempt to perform an unauthorized operation". I believe this is because on install the appDir folder is created using Administrator permissions and on run-time myApp.exe tries to write using User permissions.

Q1: How can I modify the setup project so that it can create the appDir with User writing access?

OR

Q2: How can I write the code so that the system allows me to create a new file regardless of access permissions?

Can anyone please help me with this issue?
Thank you!

PS: I've tried this and it fails as well:
DirectoryInfo dInfo = new DirectoryInfo(Application.StartupPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
FileSystemAccessRule fsar = new FileSystemAccessRule(
WindowsIdentity.GetCurrent().Name,
FileSystemRights.WriteData,
AccessControlType.Allow);
dSecurity.AddAccessRule(fsar);
dInfo.SetAccessControl(dSecurity);

Answers (3)