C#读取写入config配置文件(以winform为例)-上

本文介绍了如何在C#中读取和写入.exe.config文件的appSettings和connectionStrings部分,包括获取特定键的值、添加或更新键值对,并提供了相关代码示例。
摘要由CSDN通过智能技术生成


前言

楼主的上一篇文章写了关于ini配置文件的读取和写入的方法,在之后的冲浪过程中又发现一种很常见的配置文件,在我们没新建一个项目的时候,visual studio默认会为我们的程序集弄一个配置文件,名字就叫做App.config,里面默认记录了当前framework的版本,debug或者release之后,会在根目录生成一个叫做 ”程序集名称.exe.config“ 的配置文件。


在这个特殊的配置文件里面,已经给我们规定好了各个节点的名称,不能随便起,可以写一个小于号慢慢摸索,常见的组织结构如下,还有很多其他的固定节点,也可以自己慢慢尝试。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>

	<appSettings>
  <add key="jdk" value="hello world" />
  <add key="Cpp" value="YYDS" />
 </appSettings>

	<connectionStrings>
		<add name="sql" connectionString="sever=.;database=ufo;user=sa;pwd=123"/>
	</connectionStrings>
	
</configuration>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
</configuration>

二、使用步骤

1.读取appSettings配置节点下的指定key的value值

代码如下(示例):

 ///<summary> 
 ///返回*.exe.config文件中appSettings配置节的value项  
 ///</summary> 
 ///<param name="strKey"></param> 
 ///<returns></returns> 
 public static string GetAppConfig(string strKey)
 {
     string file = System.Windows.Forms.Application.ExecutablePath;
     Configuration config = ConfigurationManager.OpenExeConfiguration(file);
     foreach (string key in config.AppSettings.Settings.AllKeys)
     {
         if (key == strKey)
         {
             return config.AppSettings.Settings[strKey].Value.ToString();
         }
     }
     return null;
 }

 private void btnReadConfig_Click(object sender, EventArgs e)
 {
     textBox1.Text =  GetAppConfig("Cpp");
 }

2.在*.exe.config文件中appSettings配置节增加/更新一对键值对

代码如下(示例):

///<summary>  
///在*.exe.config文件中appSettings配置节增加一对键值对  
///</summary>  
///<param name="newKey"></param>  
///<param name="newValue"></param>  
public static void UpdateAppConfig(string newKey, string newValue)
{
    string file = System.Windows.Forms.Application.ExecutablePath;
    Configuration config = ConfigurationManager.OpenExeConfiguration(file);
    bool exist = false;
    foreach (string key in config.AppSettings.Settings.AllKeys)
    {
        if (key == newKey)
        {
            exist = true;
        }
    }
    if (exist)
    {
        config.AppSettings.Settings.Remove(newKey);
    }
    config.AppSettings.Settings.Add(newKey, newValue);
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
}

private void btnWriteConfig_Click(object sender, EventArgs e)
{
    UpdateAppConfig("Cpp", "YYDS");
}

3.others

4.1 读取connectionStrings配置节

///<summary>
///依据连接串名字connectionName返回数据连接字符串
///</summary>
///<param ></param>
///<returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString = 
        ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
    Console.WriteLine(connectionString);
    return connectionString;
}

4.2 更新connectionStrings配置节

///<summary>
///更新连接字符串
///</summary>
///<param >连接字符串名称</param>
///<param >连接字符串内容</param>
///<param >数据提供程序名称</param>
private static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
{
    bool isModified = false;    //记录该连接串是否已经存在
    //如果要更改的连接串已经存在
    if (ConfigurationManager.ConnectionStrings[newName] != null)
    {
        isModified = true;
    }
    //新建一个连接字符串实例
    ConnectionStringSettings mySettings = 
        new ConnectionStringSettings(newName, newConString, newProviderName);
    // 打开可执行的配置文件*.exe.config
    Configuration config = 
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // 如果连接串已存在,首先删除它
    if (isModified)
    {
        config.ConnectionStrings.ConnectionStrings.Remove(newName);
    }
    // 将新的连接串添加到配置文件中.
    config.ConnectionStrings.ConnectionStrings.Add(mySettings);
    // 保存对配置文件所作的更改
    config.Save(ConfigurationSaveMode.Modified);
    // 强制重新载入配置文件的ConnectionStrings配置节
    ConfigurationManager.RefreshSection("ConnectionStrings");
}

4.3 读取appStrings配置节

///<summary>
///返回*.exe.config文件中appSettings配置节的value项
///</summary>
///<param ></param>
///<returns></returns>
private static string GetAppConfig(string strKey)
{
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == strKey)
        {
            return ConfigurationManager.AppSettings[strKey];
        }
    }
    return null;
}

4.4 更新connectionStrings配置节

///<summary>
///在*.exe.config文件中appSettings配置节增加一对键、值对
///</summary>
///<param ></param>
///<param ></param>
private 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");
}

C#读写app.config中的数据

总结

按道理来说到这里config类型的配置文件的读取和写入也差不多了,但是楼主在浏览此类问题的时候,发现一个博主写得很好,是我想要的文章,之前也说过,这个config配置文件被编译出来就是”程序集名称.exe.config“,这篇博客默认就是读取这个文件,实在是不够自由。直到我看到一篇博客《C# 读写自定义的Config文件》链接
楼主会在下一篇博客中写出来,敬请期待

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
WinForm读取Oracle配置文件,可以按照以下步骤进行: 1. 首先,确保已经正确安装了Oracle客户端,并配置好了环境变量。这样才能在WinForm中正确访问Oracle数据库。 2. 在WinForm的项目中添加一个配置文件,可以命名为“App.config”,这个文件将用于存储Oracle数据库的连接信息。 3. 在配置文件中添加以下代码,用于配置Oracle数据库的连接信息: ```xml <configuration> <appSettings> <add key="OracleConnectionString" value="Data Source=数据库地址;User ID=用户名;Password=密码;"/> </appSettings> </configuration> ``` 其中,将“数据库地址”替换为实际的Oracle数据库地址、“用户名”替换为要连接的数据库的用户名、“密码”替换为对应的密码。 4. 在WinForm中的代码中,可以通过以下方法读取配置文件中的连接信息: ```csharp string connectionString = ConfigurationManager.AppSettings["OracleConnectionString"]; ``` 这样就可以获取到配置文件中存储的Oracle数据库的连接字符串。 5. 使用获取到的连接字符串进行数据库操作,例如连接数据库、执行SQL语句等。 需要注意的是,配置文件中的连接信息可以根据实际情况进行修改,以适应不同的Oracle数据库连接需求。另外,在代码中访问配置文件需要引用`System.Configuration`命名空间。 以上就是在WinForm读取Oracle配置文件的基本步骤。通过配置文件,在不同环境下可以方便地修改连接信息,使得程序更加灵活和易于维护。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值