首页 > 移动平台 > 详细

App.config 动态编辑

时间:2020-03-25 16:31:04      阅读:55      评论:0      收藏:0      [点我收藏+]

技术分享图片

using System.Configuration

Configuration _config;
string _paraPath = "Path";

public MainWindow()
{
    InitializeComponent();
    this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    InitConfig();
    // E:\Repository\****.csproj
    string filePath = _config.AppSettings.Settings[_paraPath].Value;
    GetData(filePath);
}
private void Dispatcher_ShutdownStarted(object sender, EventArgs e)
{
    _config.AppSettings.Settings[_paraPath].Value = txtDir.Text;
    _config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
}

private void InitConfig()
{
    try
    {
        ExeConfigurationFileMap map = new ExeConfigurationFileMap();
        Assembly assembly = Assembly.GetCallingAssembly();
        Uri uri = new Uri(Path.GetDirectoryName(assembly.CodeBase));
        string configName = Path.Combine(uri.LocalPath, assembly.GetName().Name + ".exe.config");
        if (!File.Exists(configName))
        {
            XmlDocument xml = new XmlDocument();
            xml.AppendChild(xml.CreateXmlDeclaration("1.0", "utf-8", null));
            xml.AppendChild(xml.CreateElement("configuration"));
            xml.Save(configName);
            map.ExeConfigFilename = configName;
            _config = ConfigurationManager.OpenMappedExeConfiguration(map, 0);
            _config.AppSettings.Settings.Add(_paraPath, @"E:\Repository\****.csproj");
        }
        else
        {
            map.ExeConfigFilename = configName;
            _config = ConfigurationManager.OpenMappedExeConfiguration(map, 0);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void GetData(string filePath)
{
    txtDir.Text = filePath;
}

App.config 动态编辑

原文:https://www.cnblogs.com/wesson2019-blog/p/12566202.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!