2009-12-31 115 views
4

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

任何想法,即使路径正确,我仍无法访问该文件?但在安装它创建文件和文件夹就好了?

我有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(); 

感谢

+0

您确定该程序是以管理员身份运行吗? – 2009-12-31 21:46:38

+0

非常感谢大家。我完全失去了!有趣的是看到这个应用程序数据文件夹! – user53885 2010-01-01 05:51:11

回答

4

因为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

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

3

改为使用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; 
    } 
+1

如果目录已经存在,'CreateDirectory'不会抛出,所以你不需要单独检查。 – SLaks 2009-12-31 22:52:46

相关问题