开发者

Unauthorized Access Exception in Windows 7

开发者 https://www.devze.com 2022-12-15 09:10 出处:网络
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. H

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
     开发者_如何学C  StreamWriter writer2 = new StreamWriter(path + "License.lic");
       string str = Convert.ToBase64String(sharedkey.Key);
       writer2.WriteLine(str);
       writer2.Close();

Thanks


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));


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");
        System.IO.Directory.CreateDirectory(dir);

        return dir;
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号