Unauthorized access exception in Windows 7

I have an application that reads a license file when it starts. My installation creates a folder in the Program Files for the application, creates a folder with a license and places the license file there. However, when I try to run the application, it needs to read / update the license file. When I try to do this, I get an "unauthorized access exception". I am registered as an administrator and I run the program manually.

Any idea why I cannot access this file, even if the path is correct? But in the installation, it creates a file and a folder just fine?

I have MyApplication.exe, and my license reader is in a separate DLL called MyApplicationTools. I read / write the license file as follows:

//Read StreamReader reader = new StreamReader(path + "license.lic"); //Write StreamWriter writer2 = new StreamWriter(path + "License.lic"); string str = Convert.ToBase64String(sharedkey.Key); writer2.WriteLine(str); writer2.Close(); 

thanks

+4
source share
3 answers

Due to UAC, your program does not receive administrative privileges.

Right-click the program, select "Run as administrator" and try again.
You can also create a manifest that tells Windows that it always starts as an administrator .
However, you should consider placing the license file in the AppData user folder, which does not require administrative rights.


By the way, you should use the Path.Combine method to create paths.
Also, if you just want to write one line to a file, you should call File.WriteAllText .
For instance:

 File.WriteAllText(Path.Combine(path, "License.lic"), Convert.ToBase64String(sharedkey.Key)); 
+4
source

Use AppData instead. There is an environment variable for this. You can see this by going to Explorer and typing% appdata%. It will take you to the appropriate folder. To access this in C #, I wrote the following function.

  /// <summary> /// Gets the path where we store Application Data. /// </summary> /// <returns>The Application Data path</returns> public static string GetAppDataPath() { string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); dir = System.IO.Path.Combine(dir, "MyCompany\\MyApplication"); System.IO.Directory.CreateDirectory(dir); return dir; } 
+3
source

You need to put files with write access to the user's application folder - Program Files is not writable by ordinary users. Iirc, in Win7, the default is C: \ Users \ [username] \ AppData \ [appname]. You should not run as an administrator to write to Program Files.

+2
source

All Articles