1

我有一个在 app.config 文件中存储单个用户名和密码的应用程序。我目前有 app.config 在运行时可写,以便用户能够更改它。

问题从使用安装项目安装时开始,app.config 安装在任何用户都不可写的程序文件上。

因此,我在安装时将 app.config 位置更改为公共文件夹,以便所有用户都可以读取和写入。

现在,在安装时,存储在那里的数据似乎根本无法访问,例如使用 ConfigurationManager.AppSettings["networkPath"] 返回空字符串。

我究竟做错了什么 ?

4

1 回答 1

0

你可以通过两种方式做到这一点:

  1. 由您的安装程序授予程序文件中的应用程序配置文件的特殊权限。我们使用 innosetup 来完成。如果您无能为力,请从程序启动开始:

    static void Main()
    {
        GrantAccess()
    }
    
    private static bool GrantAccess()
    {
        FileInfo fInfo = new FileInfo(Assembly.GetEntryAssembly().Location + ".config");
        FileSecurity dSecurity = fInfo .GetAccessControl();
        fSecurity.AddAccessRule(new FileSystemAccessRule("everyone", 
                                                         FileSystemRights.FullControl, 
                                                         AccessControlType.Allow));
        fInfo .SetAccessControl(fSecurity);
        return true;
    }
    
  2. 否则,您可以选择另一个位置来放置您的 appconfig 文件,然后像这样读取它:

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    fileMap.ExeConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), Assembly.GetEntryAssembly().GetName().Name) + ".exe.config";
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
                                                                           ConfigurationUserLevel.None);
    return config.AppSettings.Settings["Key"].Value);
    

在我看来,这是一个糟糕的选择。

于 2012-05-08T19:44:24.467 回答