配置文件

配置文件使用知识整理

Posted by LCY on August 23, 2018

在做程序开发的时候,一般都会使用到配置文件,包含一些可能会经常修改的变量,如果直接写进程序中,可能不便于修改和维护,因此需要一个单独的文件来做这部分工作,相当于模块式的开发,这是我个人的鄙见,可能不是那么的准确。接下来,我们来看看对配置文件的常见操作和使用过程。

常见配置文件拓展名

  • XML:C#一般是用XML来记录
  • TXT:用来配置没见过,做也是可以,不过估计要用的文本处理来读取
  • INI: 可以用WIN API来读取

针对winform,因此选择使用XML来存储配置文件是一个比较好的选择,因为在C#中有专门的类来读取XML文件,有先天的优势。

添加config文件

visual studio 2017中,新建winform解决方案时,都会自动添加配置文件,缺省名为APP.config,为标准的xml文件,其他版本如没有自动添加,可以自己手动的添加。

向config文件添加数据

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <connectionStrings>
        <add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
    </connectionStrings>
    <appSettings>
        <add key="name" value="liaochengyu"/>
        <add key="age" value="24"/>
    </appSettings>
</configuration>
  • connectionStrings节点中一般放置数据库连接字符串,可以参考msdn,关键字 ConfigurationManager.ConnectionStrings Property
  • appSettings节点中放置一般变量

在winform中读取配置文件中的数据

  • 引进 System.Configuration.dll
  • 添加命名空间 System.Configuration
  • 使用参照一下代码,主要就是 ConfigurationManager的使用
读取ConnectionStrings节点
string str = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString.ToString();
label1.Text = str;
读取appSettings节点
string name = ConfigurationManager.AppSettings["name"];
int age = Convert.ToInt32(ConfigurationManager.AppSettings["age"]);
label1.Text = name+age.ToString();

note:保存的数据都是 string类型,根据实际的需要,使用Convert.X函数来更改数据类型,在我现在做的项目中,主要使用的还是读取配置文件中的数据,写入数据的比较少,下面提供了写入和删除已有数据的方法。

在winform中保存配置文件中的数据

ConfigurationManager.AppSettings.Set("name", "lcy");
string name = ConfigurationManager.AppSettings["name"];
label1.Text = name;

运行结果: lcy

  • 一切看起来都非常简单,没有什么问题,打印出来显示都是正确的,由原来的liaochengyu修改成了lcy。实际上他设置的时候并没有真正写入xml, 而是修改了 内存中的值而已!那究竟该怎么修改xml中的数据呢?

  • 注意,正确的做法是,把配置文件按照普通的xml文件来进行修改,否则,经常出现的问题就是你所修改的东西其实最后根本没有写入文件!最后还是修改失败!可用代码

向AppConfig中添加和修改数据
public static void UpdateAppConfig(string newKey, string newValue)
{
    bool isModified = false;
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == newKey)
        {
            isModified = true;
        }
    }

    // Open App.Config of executable
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // You need to remove the old settings object before you can replace it
    if (isModified)
    {
        config.AppSettings.Settings.Remove(newKey);
    }
    // Add an Application Setting.
    config.AppSettings.Settings.Add(newKey, newValue);
    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);
    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}   

note:写配置文件都是写到exe.config文件中了,app.config不会变化。 app.config只在exe.config丢失的情况下在开发环境中重新加载app.config

删除AppConfig中已有数据
public static void DeletNode(string key)
{        
    //提供需要删除key的值

    // Open App.Config of executable
    Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   
    // You need to remove the old settings object before you can replace it
    config.AppSettings.Settings.Remove(key);
    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);
    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}

参考链接