Windows 7中未经授权的访问exception

我有一个应用程序在启动时读取许可证文件。 我的安装在应用程序的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(); 

谢谢

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

右键单击该程序,单击“以管理员身份运行”,然后重试。
您还可以创建一个清单,告诉Windows始终以管理员身份运行 。
但是,您应该考虑将许可证文件放在用户的AppData文件夹中,该文件夹不需要管理员权限。


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

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

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

  ///  /// Gets the path where we store Application Data. ///  /// The Application Data path 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; } 

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