Unauthorized Access Exception in Windows 7

风格不统一 提交于 2020-01-14 11:58:53

问题


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


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/1987232/unauthorized-access-exception-in-windows-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!