【问题标题】:How to place the exe.config file in the AppData in the installation?安装时如何将exe.config文件放在AppData中?
【发布时间】:2019-02-15 14:56:05
【问题描述】:

我用 Visual Stuido 2013 用 C# 开发了一个 Windows 窗体程序。安装后,我希望 exe.config 文件位于 AppData 路径中。因为有时程序必须读取和写入该文件,而我不希望程序必须以管理员权限执行。

当我使用安装项目创建安装程序时,我将“程序的主要输出”添加到应用程序文件夹中,但我无法指定 exe.config 可以放入 AppData 路径中。

有没有办法避免管理员权限?

谢谢。

【问题讨论】:

  • 考虑另一种模型,您可以单独保留配置文件并管理一个单独的 xml 文件,其中包含 AppData 路径中的设置 - 只是一个建议。您可以使用ConfigurationManager.OpenExeConfiguration (docs.microsoft.com/en-us/dotnet/api/…) 从非标准位置读取配置文件。如果您想将其放置在特定位置,则需要将其作为安装程序的一部分
  • 好的,谢谢!这似乎是一个很好的解决方案。但是我有疑问;我有一个带有 EntityFramework 的层,它自动从 exe.config 中获取 connectionString。我该怎么做才能使 EntityFramwork 转到字符串连接的“新 cofing”?
  • 我不是 EF 专家,但我很确定您可以覆盖自动行为。写一点GetConnectionString 例程。它首先使用正常机制。然后,如果 AppData 中有一个覆盖设置文件,并且它有一个连接字符串,它只会从那里加载它并返回那个(或者反过来,不管你觉得什么)。连接字符串只是一个字符串。现在,如果您对连接字符串部分进行了加密,它会变得更加有趣。是加密的吗?您可能想在您的问题中添加“EF”和“连接字符串”
  • 是的,实际上我正在加密所有配置文件,这就是我在开始时编写它的原因。代码是: private void EncryptarAppConfig() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.ConnectionStrings.SectionInformation.ProtectSection(null); config.Save(ConfigurationSaveMode.Full, true); }
  • 我还会在问题中添加EF和连接字符串,谢谢你的建议,Flydog57

标签: c# visual-studio winforms entity-framework connection-string


【解决方案1】:

使用系统配置; 使用 System.IO;

    Configuration config = null;

    public Program()
    {       
        string app_data = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

        StreamWriter sw = new StreamWriter(app_data + "\\MyApp.exe.config", false);
        sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        sw.WriteLine("<configuration>");
        sw.WriteLine("</configuration>");
        sw.Close();

        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = app_data + "\\MyApp.exe.config";
        config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

        config.AppSettings.Settings.Add("Key", "Value");
        config.Save();

        Console.ReadLine();
    }

【讨论】:

  • 谢谢加布里埃尔,将appconfig放在AppData中将是解决问题的方法。我的问题是在WF中安装appconfig时无法加密,您必须在第一次执行代码时进行加密。因此,这样一来,应用路径中的 appconfig 将始终未加密。
【解决方案2】:

为什么不直接在 AppData 中安装应用程序?

        string[] files = Directory.GetFiles(".\\");

        string app_data = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Apps\\MyApp";
        Directory.CreateDirectory(app_data);

        foreach (var file in files)
        {
            File.Copy(file, app_data + file.Substring(file.LastIndexOf("\\")) );
        }  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多