【问题标题】:Unauthorized Access Exception in Windows 7Windows 7 中的未授权访问异常
【发布时间】:2009-12-31 21:44:37
【问题描述】:

我有一个应用程序,它在启动时会读取许可证文件。我的安装在 Program Files 中为应用程序创建文件夹,创建许可证文件夹并将许可证文件放在那里。但是,当我尝试运行该应用程序时,它需要读取/更新许可证文件。当我尝试这样做时,我得到一个“未经授权的访问异常”。我以管理员身份登录并手动运行程序。

知道为什么即使路径正确我也无法访问该文件?但是在安装中它创建的文件和文件夹就好了吗?

我有 MyApplication.exe,我的许可证阅读器位于一个名为 MyApplicationTools 的单独 DLL 中。我正在像这样读/写许可证文件:

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

谢谢

【问题讨论】:

  • 您确定程序是以管理员身份运行的吗?
  • 非常感谢大家。我完全离开了!看到这个应用数据文件夹很有趣!

标签: c# windows-7 x86-64


【解决方案1】:

由于 UAC,您的程序没有获得管理权限。

右键单击该程序,单击以管理员身份运行,然后重试。
你也可以create a manifest that tells Windows to always run as Administrator.
但是,您应该考虑将许可文件放在用户的 AppData 文件夹中,这不需要管理权限。


顺便说一句,您应该使用Path.Combine 方法来创建路径。
此外,如果您只想将单个字符串写入文件,则应调用 File.WriteAllText
例如:

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

【讨论】:

    【解决方案2】:

    改用 AppData。为此有一个环境变量。您可以通过进入资源管理器并输入 %appdata% 来查看。它会将您带到相应的文件夹。为了在 C# 中访问它,我编写了以下函数。

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

    【讨论】:

    • CreateDirectory如果目录已经存在则不会抛出,所以不需要单独检查。
    【解决方案3】:

    您需要将可写文件放在用户应用程序文件夹中 - 普通用户无法写入 Program Files。 Iirc,在 Win7 上,默认位置是 C:\Users\[username]\AppData\[appname]。您不应该仅仅为了写入程序文件而以管理员身份运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      相关资源
      最近更新 更多