【C#】【WPF】如何读写app.config文件

WPF生成的项目中会有.exe.config。一般是系统默认配置的

格式是xml格式,C#的项目可以直接读写这些文件。方法代码如下。

public static string GetConnectionStringsConfig(string connectionName)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            System.Configuration.Configuration sysconfig = ConfigurationManager.OpenExeConfiguration(file);
            string connectionString =
                sysconfig.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
            return connectionString;
        }
public static void UpdateConnectionStringsConfig(string newName, string newConString)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration sysconfig = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            if (sysconfig.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            if (exist)
            {
                sysconfig.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString);
            sysconfig.ConnectionStrings.ConnectionStrings.Add(mySettings);
            sysconfig.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }

以上方法可以直接向配置文件中动态写入。

 

 

还有一种方法是使用Key值的config读写

app.config的配置文件如下

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="Language" value="Chinese" />
    <add key="DefaultConfigPath" value="" />
    <add key="DBFilePath" value="" />
  </appSettings>
</configuration>

读配置文件的方法很简单,代码如下

language = ConfigurationManager.AppSettings[Options.Language];
defaultConfigPath = ConfigurationManager.AppSettings[Options.DefaultConfigPath];
dbFilePath = ConfigurationManager.AppSettings[Options.DBFilePath];

写入配置文件的方法也很简单,方法如下

        public static void WriteOptions(string keyName, string newValue)
        {
            Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            cfa.AppSettings.Settings[keyName].Value = newValue;
            cfa.Save();
        }

调用方法完成写入指定Key值的配置文件。

这种方法仅仅在配置文件中存在指定Key值的时候可以写入Value的值。也就是修改指定Key的对应Value的值。

当然对应还有删除和添加的方法如下

public static void WriteOptions(string keyName, string newValue)
{
       Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
       //删除
       cfa.AppSettings.Settings.Remove(KeyName);
       //添加
       cfa.AppSettings.Settings.Add(KeyName,newValue);
       cfa.Save();
}

 

转载于:https://www.cnblogs.com/duan425/p/5645774.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值