views:

208

answers:

3

Hello,

I have an application which reads a license file when it starts up. My install creates the folder in Program Files for the application, creates the license folder and puts the license file in there. However when I try and run the application, it needs to read/update the license file. When I try and do that I get an "Unauthorized Access Exception". I am logged on as an administrator and I'm running the program manually.

Any idea why I cannot access that file even though the path is correct? But in the install it creates the file and folder just fine?

I have MyApplication.exe, and my license reader is in a seperate DLL called MyApplicationTools. I am reading/write the license file like so:

       //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

+3  A: 

Because of UAC, your program isn't getting administrative privileges.

Right-click the program, click Run as Administrator, and try again.
You can also create a manifest that tells Windows to always run as Administrator.
However, you should consider putting the license file in the user's AppData folder, which does not require administrative privileges.


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

File.WriteAllText(Path.Combine(path, "License.lic"), Convert.ToBase64String(sharedkey.Key));
SLaks
+2  A: 

You need to put writable files in a User application folder - Program Files is not writable by ordinary users. Iirc, on Win7 the default location is C:\Users\[username]\AppData\[appname]. You shouldn't be running as administrator just to write into Program Files.

DaveE
+2  A: 

Use AppData instead. There is an environment variable for this. You can see this by going into explorer and typing %appdata%. It'll take you to the appropriate folder. To access this in C# I've written 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");
        if (!System.IO.Directory.Exists(dir))
        {
            System.IO.Directory.CreateDirectory(dir);
        }

        return dir;
    }
McAden
`CreateDirectory` will not throw if the directory already exists, so you don't need to check separately.
SLaks