.NET配置文件读写实例(附SosoftConfigHelper类)

配置文件在软件开发中起到举足轻重的作用,可以说不可或缺。.NET程序可使用.config文件作为配置文件,例如WinForm程序的*.app.config、Web程序的web.config。.config文件是标准的XML文件。本实例可读取、修改和添加app.confing或者web.config文件的appSettings。SosoftConfigHelper类还可以读写ConnectionStrings。

使用Visual Studio创建一个WinForm项目,在窗体上建立控件,如图:

键值列表中的值是运行结果。

然后在更新配置按钮事件方法中加入如下代码:

SosoftConfigHelper.UpdateAppConfig(textBox_key.Text, textBox_value.Text);

窗体的代码如下:

/*
Copyright (c) 2012  柔城  All rights reserved.* * sosoft.cnblogs.com*/
using System;
using System.Configuration;
using System.Windows.Forms;
using Sosoft.Cnblogs.Com.Helper;namespace Sosoft.Cnblogs.Com
{public partial class MainForm : Form{public MainForm(){InitializeComponent();}private void button_update_Click(object sender, EventArgs e){SosoftConfigHelper.UpdateAppConfig(textBox_key.Text, textBox_value.Text);GetKeyValueList();}private void GetKeyValueList(){textBox_keyValueList.Text = string.Empty;foreach (string key in ConfigurationManager.AppSettings){textBox_keyValueList.Text += key + " : " + SosoftConfigHelper.GetAppConfig(key) + "\r\n";}}private void MainForm_Load(object sender, EventArgs e){GetKeyValueList();}}
}

记得要添加System.Configuration命名空间和程序集的引用。

另外新建一个类,命名SosoftConfigHelper.cs,这是配置文件读写类,代码如下:

  1 /*
  2 Copyright (c) 2012  柔城  All rights reserved.
  3  * 
  4  * sosoft.cnblogs.com
  5  */
  6 using System;
  7 using System.Configuration;
  8 
  9 namespace Sosoft.Cnblogs.Com.Helper
 10 {
 11     /// <summary>
 12     /// Sosoft配置文件辅助类
 13     /// </summary>
 14     public class SosoftConfigHelper
 15     {
 16         /// <summary>
 17         ///  读取appStrings配置节, 返回*.exe.config文件中appSettings配置节的value项
 18         /// </summary>
 19         /// <param name="strKey"></param>
 20         /// <returns></returns>
 21         public static string GetAppConfig(string strKey)
 22         {
 23             foreach (string key in ConfigurationManager.AppSettings)
 24             {
 25                 if (key == strKey)
 26                 {
 27                     return ConfigurationManager.AppSettings[strKey];
 28                 }
 29             }
 30             return null;
 31         }
 32 
 33 
 34         /// <summary>
 35         /// 更新appStrings配置节,在*.exe.config文件中appSettings配置节增加一对键、值对
 36         /// </summary>
 37         /// <param name="newKey"></param>
 38         /// <param name="newValue"></param>
 39         public static void UpdateAppConfig(string newKey, string newValue)
 40         {
 41             bool isModified = false;
 42             foreach (string key in ConfigurationManager.AppSettings)
 43             {
 44                 if (key == newKey)
 45                 {
 46                     isModified = true;
 47                 }
 48             }
 49 
 50             // Open App.Config of executable
 51             Configuration config =
 52                 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 53             // You need to remove the old settings object before you can replace it
 54             if (isModified)
 55             {
 56                 config.AppSettings.Settings.Remove(newKey);
 57             }
 58             // Add an Application Setting.
 59             config.AppSettings.Settings.Add(newKey, newValue);
 60             // Save the changes in App.config file.
 61             config.Save(ConfigurationSaveMode.Modified);
 62             // Force a reload of a changed section.
 63             ConfigurationManager.RefreshSection("appSettings");
 64         }
 65 
 66 
 67 
 68         /// <summary>
 69         /// 读取connectionStrings配置节,依据连接串名字connectionName返回数据连接字符串
 70         /// </summary>
 71         /// <param name="connectionName"></param>
 72         /// <returns></returns>
 73         public static string GetConnectionStringsConfig(string connectionName)
 74         {
 75             string connectionString =
 76                     ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
 77             Console.WriteLine(connectionString);
 78             return connectionString;
 79         }
 80 
 81 
 82         /// <summary>
 83         /// 更新connectionStrings配置节, 更新连接字符串
 84         /// </summary>
 85         /// <param name="newName"> 连接字符串名称 </param>
 86         /// <param name="newConString"> 连接字符串内容 </param>
 87         /// <param name="newProviderName"> 数据提供程序名称 </param>
 88         public static void UpdateConnectionStringsConfig(string newName,
 89             string newConString,
 90             string newProviderName)
 91         {
 92             bool isModified = false;    // 记录该连接串是否已经存在
 93             // 如果要更改的连接串已经存在
 94             if (ConfigurationManager.ConnectionStrings[newName] != null)
 95             {
 96                 isModified = true;
 97             }
 98             // 新建一个连接字符串实例
 99             ConnectionStringSettings mySettings =
100                 new ConnectionStringSettings(newName, newConString, newProviderName);
101             // 打开可执行的配置文件*.exe.config
102             Configuration config =
103                 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
104             // 如果连接串已存在,首先删除它
105             if (isModified)
106             {
107                 config.ConnectionStrings.ConnectionStrings.Remove(newName);
108             }
109             // 将新的连接串添加到配置文件中.
110             config.ConnectionStrings.ConnectionStrings.Add(mySettings);
111             // 保存对配置文件所作的更改
112             config.Save(ConfigurationSaveMode.Modified);
113             // 强制重新载入配置文件的ConnectionStrings配置节
114             ConfigurationManager.RefreshSection("ConnectionStrings");
115         }
116     }
117 }

最后右击项目选择“添加-新建项”,然后选择“应用程序配置文件”,点击添加按钮就创建配置文件app.config。

app.config的格式如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration><appSettings><add key="SosoftKey" value="sosoftValue" /><add key="SosoftURL" value="sosoft.cnblogs.com" /><add key="SosoftProject" value="sosoft.codeplex.com" /></appSettings>
</configuration>

按F5运行,可以添加、修改appSettings配置项和列出所有appSettings配置项。

 

柔城配置文件读写实例源代码下载地址:http://files.cnblogs.com/sosoft/SosoftConfig.rar

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/548302.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于shared_from_this的转换

声明&#xff1a;以下这函数&#xff0c;使用场景再lambda表达式中使用 std::weak_ptr<websockets_session> weak_self() { return std::weak_ptr<websockets_session>(shared_from_this()); }

HTML5标签

<header>主要用于导航&#xff0c;头部&#xff0c;可以嵌套&#xff0c;但不可以嵌套在<address>标签中。 <hgroup>在<header>里面定义具体内容的&#xff0c;是一个小容器。 <article></article>:大块文章&#xff0c;主要用于文字的显示…

多态的调用方法

1: 父类的指针指向子类的地址&#xff0c;然后调用虚函数 列子: #include<iostream> #include<memory> class A { public: A() default; virtual ~A() default; virtual void display() { std::cout << "A" <<…

spring security3 统计在线用户

首先&#xff0c;我们需要使得ConcurrentSessionFilter生效并在spring-security.xml配置。[html] view plaincopy<http auto-config"true" use-expressions"true"> <!-- Uncomment to limit the number of sessions a user can have --> …

node.js编程错误记录集

这是有关于我最近学习node.js中出现的错误的记录和纠正过程&#xff0c;因为我只是一名初学者&#xff0c;所以&#xff0c;遇到的错误可能真的是非常简单&#xff0c;如拼写错误等等&#xff0c;这些我当然是不会记录下来的&#xff0c;但是如果是一些我一时看不懂&#xff0c…

wstring和string简单正则表达式使用

std::regex e("([ ])3DSMAX(\d{4})_MAIN([^ ])"); //std::regex e("([^ ])3DSMAX(\d{4})_MAIN"); std::smatch sub_match; //从第一行中解析请求方法、路径和 HTTP 版本 std::string line “VRAY30_RT_FOR_3DSMAX2016_MAIN”; if (std::regex_match(line,…

【引用】phpmyadmin提示Access denied for user 'root'@'localhost' (using password: NO)的解决办法...

一、错误内容 今天用phpmyadmin连接mysql里面的某个数据库时时遇到了下面的提示&#xff1a; #1045 - Access denied for user rootlocalhost (using password: NO) phpMyAdmin 试图连接到 MySQL 服务器&#xff0c;但服务器拒绝连接。您应该检查 config.inc.php 中的主机、用户…

Nuget 启用数据库迁移的时候一定要把包含DbContext的项目设为启动项目

在为项目启用数据库迁移的时候&#xff08;enable-migrations&#xff09;出现如下错误&#xff1a; 在程序集“XX”中未找到迁移配置类型“XX.Migrations.Configuration” 之前一直正确的&#xff0c;并没有修改项目中的代码&#xff0c;花了小半天找原因&#xff0c;stackove…

string、wstring、UTF-8、UTF-16、UTF-32之间转换

//string转wstring std::wstring string_to_wstring(const std::string& str) { setlocale(LC_ALL, “”); std::int64_t size mbstowcs(NULL, str.c_str(), 0); std::wstring w_str; w_str.resize(size); //算出代转wstring字节 mbstowcs(w_str.data(), str.c_str(), str…

论贱人

来源于我在论坛的一帖&#xff0c;个中缘由不说也罢。<<论贱人>> 天地阴阳&#xff0c;构精而生万物&#xff0c;万物生而后人生。物有性格&#xff0c;人亦有性格。性有善恶之分&#xff0c;格有贵贱之别。古人尝论人性之善恶&#xff0c;孟子云人性本善&#xff…

Delphi用ini文档实现界面无闪烁多语言转换

越来越多的程序使用了多国语言切换&#xff0c;虽然DELPHI自带多语言包的添加和配置&#xff0c; 但是那种方法在切换语言时界面会出现闪烁&#xff0c;而且实现起来很麻烦&#xff0c;这里我介绍给大家的是利用INI文件来读取界面的语种文字&#xff0c; 用这种方法&#x…

vi交互式批量替换 vi批量替换 vi查找和替换

vi中如何实现批量替换&#xff1f; 举个例子啊&#xff1a; 将文件tihuan&#xff08;假设此文本中字符a&#xff09;中的所有字符a换成字符w&#xff0c;其命令为&#xff1a; 1。vi tihuan 2。按esc键 3。按shift&#xff1a; 4。在&#xff1a;后输入 %s/a/w/g 其中s为&a…

linux的开始

这个星期天我去同学聚会了&#xff0c;开封的来了个同学李永生&#xff0c;新乡的来了个同学陈凯&#xff0c;大家在周六下午在一块吃了个饭&#xff0c;虽说有些小插曲&#xff0c;&#xff08;保成的女朋友和桂林&#xff08;桂皮&#xff09;来晚了&#xff09;&#xff0c;…

内联命名空间(inline namespace)

#include<iostream> //直接使用,不需要using inline namespace B { class A { public: A() default; ~A() default; void display() { std::cout << "a" << std::endl; } }; } i…

WordPress主题制作常用代码集合

如何你是个wordpress主题设计者&#xff0c;可能会在制作wordpress主题时为了一些寻找合适的wordpress代码焦虑&#xff0c;这里搜集总结wordpress主题开发中常用的代码片段&#xff0c;希望为你工作中带来方便 最新文章最新更新文章/页面最新评论最受欢迎文章文章分类下拉框文…

电脑配置多个git账号

配置user1 Host u1.github.com HostName github.com IdentityFile C:\Users\admin\.ssh\id_rsa1 PreferredAuthentications publickey User user1 配置user2 Host u2.github.com HostName github.com IdentityFile C:\Users\admin\.ssh\id_rsa PreferredAuthentications pub…

[Effective C++读书笔记]003_条款03_尽可能使用const

参考同事博客&#xff1a;http://www.cnblogs.com/hustcser/archive/2012/10/19/2731085.html转载于:https://www.cnblogs.com/alephsoul-alephsoul/archive/2012/10/17/2727057.html

sizeof操作

C98, sizeof只能对实例的变量或者类的静态成员进行操作&#xff0c;不能对类的非静态成员进行操作&#xff0c;若要想达成对类的非静态成员的操作&#xff0c;可以用如下ugly方式, 0强转成对象的指针&#xff0c;并解析访问对应非静态成员变量。 struct SomeType { int member…

利用VMware Infrastructure SDK编程控制虚拟机集群(3)

接上回&#xff0c;继续整理针对虚拟机的各种操作。 7、跨主机克隆虚拟机 网上资料比较少&#xff0c;当时费了很大劲才成功的&#xff0c;与同一台主机上的虚拟机克隆有区别。 /// <summary> /// 从模板部署虚拟机 /// </summary> public void Deploy() { …

H3C 帧中继初级配置(二)

配置思路&#xff1a; 1、先配置FR-SWITCH 2、再配置RTA、RTB、RTC FR-SWITCH详细配置步骤如下&#xff1a; [FR-Switch]fr switching //启动路由器帧中继功能 [FR-Switch]interface s6/0 [FR-Switch-Serial6/0]link-protocol fr //链路协议封闭为FR [FR-Switch-Serial6/0]fr…