使用ConfigurationManager类 读写配置文件
- 格式:doc
- 大小:21.00 KB
- 文档页数:3
Config⽂件的使⽤:通过程序修改Config⽂件对于config⽂件,⼀般情况下都是使⽤ConfigurationManager加载,然后通过读取相应节点的值来获取想要的数据,但是,有时候需要修改config⽂件的值,这时候就⽤到了OpenExeConfiguration()⽅法。
MSDN上⾯对该⽅法的解释:ConfigurationManager.OpenExeConfiguration⽅法⽤来把指定的客户端配置⽂件作为Configuration对象打开,该⽅法具有两个重载:名称说明ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel)将当前应⽤程序的配置⽂件作为 Configuration 对象打开。
ConfigurationManager.OpenExeConfiguration (String)将指定的客户端配置⽂件作为 Configuration 对象打开。
⼀、使⽤OpenExeConfiguration(ConfigurationUserLevel)重载设置当前应⽤程序的配置⽂件客户端应⽤程序使⽤应⽤于所有⽤户的全局配置、应⽤于单个⽤户的单独配置以及应⽤于漫游⽤户的配置。
userLevel 参数通过指⽰该配置⽂件是不具有⽤户级别(配置⽂件与应⽤程序位于同⼀⽬录中),还是具有⼀个依每个⽤户⽽定的⽤户级别(配置⽂件位于⽤户级别所确定的应⽤程序设置路径中),从⽽确定所打开的配置⽂件的位置。
通过向 userLevel 传递下列值之⼀来指定要获取的配置:若要获取应⽤于所有⽤户的 Configuration 对象,请将 userLevel 设置为 None。
若要获取应⽤于当前⽤户的本地 Configuration 对象,请将 userLevel 设置为 PerUserRoamingAndLocal。
若要获取应⽤于当前⽤户的漫游 Configuration 对象,请将 userLevel 设置为 PerUserRoaming。
C#ConfigurationManager多个配置⽂件读取问题之前写了篇的⽂章,后来在实际使⽤过程中,将⼀些需要修改的参数顺⼿就写到了配置⽂件App.config⾥⾯。
然后直接F5运⾏项⽬,想着调试下看看程序是否正常运⾏,这⼀试就试出问题了,ConfigurationManager.AppSettings.Get("message")获取不到参数。
ConfigurationManagerConfigurationManager是⼀个提供对客户端应⽤程序配置⽂件访问的静态类,此类不能被继承。
使⽤此类需要先将System.Configuration.dll引⽤到项⽬中来,具体的使⽤⽅式建议查看。
回顾⼀下上⽂项⽬的⽬录结构,在⼀个解决⽅案中有两个项⽬分别为TaskWindowsService(Windows服务项⽬)和WindowsServiceClient(服务管理winform程序)。
他们都有各⾃的App.config⽂件。
接下来我们做⼀个测试:1. 各个项⽬的App.config中分别添加如下代码<appSettings><add key="message" value="this is TaskWindowsService"/></appSettings><appSettings><add key="message" value="this is WindowsServiceClient"/></appSettings>ps:(两个配置⽂件都有了,总不⾄于读不到数据了吧~)2. 在TaskWindowsService中引⽤System.Configuration.dll,并使⽤ConfigurationManager读取配置⽂件,记录到⽇志中public static void ConfigTest(){LogHelper.Log(ConfigurationManager.AppSettings.Get("message"));}3. 运⾏WindowsServiceClient并调⽤ConfigTest()⽅法public Form1(){InitializeComponent();SkpDomain.ConfigTest();}4. 注册并启动TaskWindowsService在服务启动时调⽤ConfigTest()⽅法protected override void OnStart(string[] args){SkpDomain.ConfigTest();}看⼀下输出的⽇志,好玩的东西来了。
主题:ConfigurationManager路径解析一、引言在软件开发中,ConfigurationManager是一个非常重要的工具,可以用来读取和写入应用程序的配置信息。
而在使用ConfigurationManager的过程中,经常需要获取配置文件的路径。
本文将对ConfigurationManager路径进行解析,帮助读者更好地理解和使用该工具。
二、ConfigurationManager简介1. ConfigurationManager是.Net Framework提供的一个工具类,位于System.Configuration命名空间下。
2. 通过ConfigurationManager可以轻松地读取、写入配置文件中的配置信息,如连接字符串、应用设置等。
3. 通常情况下,使用ConfigurationManager需要引用System.Configuration命名空间,并通过ConfigurationManager 类中的静态方法来进行操作。
三、获取配置文件路径在实际应用中,有时需要获取配置文件的路径,以便进行读取或写入操作。
以下是一些常见的方法来获取配置文件路径:1. 使用AppDomain.CurrentDomain.BaseDirectory属性。
例如:string configPath = AppDomain.CurrentDomain.BaseDirectory + "App.config";2. 使用AppDomain.CurrentDomain.SetupInformation.ConfigurationFile 属性。
例如:string configPath =AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;3. 使用Assembly.GetExecutingAssembly().Location属性。
configurationmanager.connectionstrings 用法-回复configurationmanager.connectionstrings是一个用于访问和管理应用程序配置文件中连接字符串的类。
在.NET开发中,连接字符串是一种用于连接到数据库、文件等存储资源的重要参数。
配置文件是一个XML 文件,通常用于存储应用程序的设置和配置信息。
本文将详细介绍configurationmanager.connectionstrings类的用法,并提供一些具体的示例来帮助读者更好地理解。
首先,我们需要引入System.Configuration命名空间,这个命名空间包含了configurationmanager.connectionstrings类。
在代码中,我们可以通过using关键字来简化命名空间的使用,即using System.Configuration。
接下来,我们需要在配置文件中定义连接字符串。
通常,配置文件的名称为App.config(Windows应用程序)或Web.config(Web应用程序),位于应用程序的根目录下。
我们可以使用任何文本编辑器来编辑配置文件。
在配置文件中,我们可以使用connectionStrings元素来定义连接字符串。
例如,以下是一个简单的连接字符串定义:<connectionStrings><add name="MyConnection"connectionString="Server=localhost;Database=MyDatabase;User Id=sa;Password=123456;" providerName="System.Data.SqlClient"/></connectionStrings>在上面的示例中,我们定义了一个名为“MyConnection”的连接字符串,它连接到本地的数据库“MyDatabase”,使用了SQL Server的提供程序“System.Data.SqlClient”。
Config程序配置⽂件(configSections)操作实践及代码详注所有与配置⽂件相关的类:(粗体为⼀般情况下使⽤到的类,其它类功能可能在很复杂的情况下才使⽤到。
)1、ConfigurationManager,这个提供⽤于打开客户端应⽤程序集的Configuration对象。
2、WebConfigurationMaManager,这个提供⽤于打开web应⽤程序集的Configuration对象。
3、ConfigurationSection ,表⽰配置⽂件中的区域对象。
4、ConfigurationSectionCollection ,表⽰配置⽂件中相关区域的集合。
5、ConfigurationSectionGroup ,表⽰配置⽂件中的⼀组相关区域的组对象。
6、ConfigurationSectionGroupCollection ,表⽰ ConfigurationSectionGroup 对象的集合。
7、ConfigurationProperty ,表⽰区域或元素的属性。
8、ConfigurationPropertyAttribute ,以声明⽅式指⽰ .NET Framework,以实例化配置属性。
9、ConfigurationElement ,表⽰配置⽂件中的元素对象。
10、ConfigurationElementCollection ,表⽰元素的集合的对象。
⽂章中只对粗体的类进⾏实践,因为已经可以涵盖80%以上的需求。
使⽤的需求环境:对于在程序中⽤到的⼀些参数配置可能会随着程序的使⽤⽽改变,如果将这些参数写在代码⾥并编译到EXE⽂件中,那这些参数的改变则⽆法得到保存。
如果下次程序启动的时候想载⼊改变后的参数配置则必须将这些参数配置写⼊到⼀个⽂件中保存。
.NET中提供了⼀个System.Configuration.dll,这个命名空间下提供的类可以很⽅便的把这些参数配置读写到XML⽂件中。
.Net读取配置⽂件xml直接解析XML⽂件在直接读取⽂件的时候由于⼿动getAttribute很⿇烦,⽽且容易出错,attribute可以参考log4net的⽅式,全部做成宏定义:使⽤.Net提供的的⽅式(ConfigurationManager类,⽀持.Net Core 2)特别说明:using System.Configuration 之后可能还要⼿动勾选,如下图:使⽤.Net 提供的⽅法读取有时候会很⽅便,可以直接将配置信息填写在app.config ⽂件中例如下⾯的配置⽂件读取的时候:<?xml version="1.0" encoding="utf-8" ?><configuration><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup><appSettings><add key="name" value="kun"/><add key="name2" value="kun"/></appSettings><connectionStrings><add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" /> </connectionStrings></configuration>static void ReadAllSettings(){try{var appSettings = ConfigurationManager.AppSettings;if (appSettings.Count == 0){Console.WriteLine("AppSettings is empty.");}else{foreach (var key in appSettings.AllKeys.Where((key) => key == "name")){Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);}}}catch (ConfigurationErrorsException){Console.WriteLine("Error reading app settings");}}static void ReadSetting(string key){try{var appSettings = ConfigurationManager.AppSettings;string result = appSettings[key] ?? "Not Found";Console.WriteLine(result);}catch (ConfigurationErrorsException){Console.WriteLine("Error reading app settings");}}读取数据库连接信息也可以只⽤⼀句代码:var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;对于这种简单key/Value⽅式的配置,使⽤ConfigurationManager类还是很⽅便的。
.Net2.0 使用ConfigurationManager读写配置文件收藏.net1.1中如果需要灵活的操作和读写配置文件并不是十分方便,一般都会在项目中封装一个配置文件管理类来进行读写操作。
而在.net2.0中使用ConfigurationManager 和WebConfigurationMan ager 类可以很好的管理配置文件,ConfigurationManager类在System.Configuration中,WebCo nfigurationManager在System.Web.Configuration中。
根据MSDN的解释,对于Web 应用程序配置,建议使用System.Web.Configuration.WebConfigurationManager 类,而不要使用System. Configuration.ConfigurationManager 类。
下面我给出一个简单的例子说明如何使用WebConfigurationManager操作配置文件://打开配置文件Configuration config = WebConfigurationManager.OpenWebConfiguration("~");//获取appSettings节点AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");//在appSettings节点中添加元素appSection.Settings.Add("addkey1", "key1's value");appSection.Settings.Add("addkey2", "key2's value");config.Save();运行代码之后可以看见配置文件中的改变:<appSettings><add key="addkey1" value="key1's value" /><add key="addkey2" value="key2's value" /></appSettings>修改和删除节点或属性也非常方便://打开配置文件Configuration config = WebConfigurationManager.OpenWebConfiguration("~");//获取appSettings节点AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");//删除appSettings节点中的元素appSection.Settings.Remove("addkey1");//修改appSettings节点中的元素appSection.Settings["addkey2"].Value = "Modify key2's value";config.Save();配置文件:<appSettings><add key="addkey2" value="Modify key2's value" /></appSettings>。
configurationmanager.connectionstrings 用法-回复configurationmanager.connectionstrings 是一种在 .NET 环境中管理数据库连接字符串的功能。
连接字符串是用来连接应用程序和数据库之间的信息,包括数据库类型、服务器名称、用户名和密码等。
configurationmanager.connectionstrings 是 .NET Framework 中System.Configuration 命名空间的一个类,它提供了一种方便的方式来读取和操作应用程序的配置信息,特别是数据库连接字符串。
在使用之前,需要将System.Configuration 添加为项目的引用,并在代码中导入命名空间using System.Configuration。
那么,如何使用configurationmanager.connectionstrings 来管理数据库连接字符串呢?下面将一步一步介绍该过程。
第一步:创建配置文件在 .NET 项目中,我们可以通过在项目根目录下添加一个名为"app.config" 或"web.config" 的XML 文件来创建配置文件。
如果是 Web 应用程序,则可以使用"web.config" 文件;如果是桌面应用程序,则可以使用"app.config" 文件。
注意:在创建配置文件时,需要将其命名为"app.config" 或"web.config",否则在读取配置信息时会出错。
第二步:添加配置信息在配置文件中,可以使用configuration 标签来标识配置信息的根节点。
在configuration 标签内,可以使用connectionStrings 标签来定义数据库连接字符串。
例如:xml<?xml version="1.0" encoding="utf-8"?><configuration><connectionStrings><add name="MyDbConnection"connectionString="Server=myServerAddress;Database=myDataBa se;UserID=myUsername;Password=myPassword;Trusted_Connection=Fals e;" providerName="System.Data.SqlClient" /></connectionStrings></configuration>在上述示例中,定义了一个名为"MyDbConnection" 的连接字符串,其中包含了连接服务器、数据库、用户名和密码等信息。
configurationmanager.connectionstrings 用法-回复如何使用configurationmanager.connectionstrings?configurationmanager.connectionstrings 是一个类,用于获取和管理应用程序的连接字符串。
连接字符串指的是用于连接到数据库或其他外部资源的信息,包括服务器名称、数据库名称、认证凭据等。
通过使用configurationmanager.connectionstrings,开发人员可以方便地获取和使用连接字符串,从而简化应用程序的开发和部署过程。
在本文中,我们将详细介绍configurationmanager.connectionstrings 的用法,并提供一些示例来帮助读者更好地理解和应用这个类。
步骤一:添加引用首先,我们需要在项目中添加对System.Configuration 程序集的引用。
这可以通过在Visual Studio 中右键单击项目,选择“添加”-> “引用”来完成。
在弹出的对话框中,选择“程序集”选项卡,并在搜索框中输入“System.Configuration”。
选择搜索结果中的System.Configuration,并单击“确定”按钮添加引用。
步骤二:配置连接字符串在应用程序的配置文件(通常是app.config 或web.config)中,我们需要配置连接字符串。
连接字符串通常以"key=value" 的形式存储在<connectionStrings> 元素的子元素中。
以下是一个示例连接字符串配置的代码片段:<connectionStrings><add name="MyConnectionString"connectionString="Server=myServerAddress;Database=myDataBa se;User Id=myUsername;Password=myPassword;" providerName="System.Data.SqlClient" /></connectionStrings>在上述代码片段中,我们定义了一个名为"MyConnectionString" 的连接字符串,并提供了服务器地址、数据库名称、用户名和密码等信息。
C#读写config配置⽂件⼀:使⽤ConfigurationManager①:添加System.configguration②:引⽤空间③:config配置⽂件配置节A:⾃定义配置B:数据源配置<addname="kyd"connectionString=“server=.;database=UFDATA_999_2017;user=sa;pwd=123”/> </connectionStrings>1C:普通配置⼆:Config⽂件读写1.依据连接串名返回字符串A:界⾯B:后台代码private void button1_Click(object sender, EventArgs e){//指定config⽂件读取string file = System.Windows.Forms.Application.ExecutablePath;System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file); string connectionString =config.ConnectionStrings.ConnectionStrings[“sql1”].ConnectionString.ToString(); MessageBox.Show( connectionString);}2.更新连接字符串A:界⾯B:后台代码private void button2_Click(object sender, EventArgs e){//////更新连接字符串//////连接字符串名称///连接字符串内容///数据提供程序名称//指定config⽂件读取string file = System.Windows.Forms.Application.ExecutablePath;Configuration config = ConfigurationManager.OpenExeConfiguration(file);bool exist = false; //记录该连接串是否已经存在//如果要更改的连接串已经存在if (config.ConnectionStrings.ConnectionStrings["sql1"] != null){exist = true;}// 如果连接串已存在,⾸先删除它if (exist){config.ConnectionStrings.ConnectionStrings.Remove("sql1");}//新建⼀个连接字符串实例ConnectionStringSettings mySettings =new ConnectionStringSettings("sql1", "Data","AA");// 将新的连接串添加到配置⽂件中.config.ConnectionStrings.ConnectionStrings.Add(mySettings);// 保存对配置⽂件所作的更改config.Save(ConfigurationSaveMode.Modified);// 强制重新载⼊配置⽂件的ConnectionStrings配置节ConfigurationManager.RefreshSection("connectionStrings");}1234567891011121314151617181920213.exe.confing⽂件中的appSettings配置节的valueA:界⾯B:后台代码private void button3_Click(object sender, EventArgs e){string file = System.Windows.Forms.Application.ExecutablePath;Configuration config = ConfigurationManager.OpenExeConfiguration(file);foreach (string key in config.AppSettings.Settings.AllKeys){if (key == “key1”){MessageBox.Show(config.AppSettings.Settings[“key1”].Value.ToString());}}}4.exe.confing⽂件中的appSettings配置节增加⼀对键值对A:界⾯B:后台代码private void button4_Click(object sender, EventArgs e){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 == “key1”){exist = true;}}if (exist){config.AppSettings.Settings.Remove(“key1”);}config.AppSettings.Settings.Add(“key1”, “5555”);config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection(“appSettings”);}⽅法2:⼀、配置⽂件概述:应⽤程序配置⽂件是标准的 XML ⽂件,XML 标记和属性是区分⼤⼩写的。
C#读取和写⼊配置⽂件使⽤.Net2.0中的ConfigurationManager可以⽅便的实现对配置app.config的读取和写⼊。
ConfigurationManager默认没有⾃动载⼊项⽬,使⽤前必须⼿动添加,⽅法如下:项⽬->引⽤->添加引⽤->选择System.configuration1.使⽤ConfigurationManager读配置⽂件我们可以将简单的配置内容放到app.config中的appSettings节点中如下:<appSettings><add key="GPRS.Port1" value="5002"/><add key="GPRS.Port2" value="5003"/><add key="GPRS.Port3" value="5004"/></appSettings>然后在程序中使⽤ConfigurationManager.AppSettings["GPRS.Port1"]来读取GPRS.Port1的值2.使⽤ConfigurationManager写配置⽂件如何想要把修改过的GPRS.Port1的值存放回app.config,可以使⽤下⾯的代码System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["GPRS.Port1"].Value = “xxxxx”;config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置⽂件。
C# 读写Config文件(App.config)读语句:String str = ConfigurationManager.AppSettings["DemoKey"];写语句:Configuration cfa =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue";cfa.Save();配置文件内容格式:(app.config)<?xml version="1.0" encoding="utf-8" ?><configuration><appSettings><add key="DemoKey" value="*" /></appSettings></configuration>System.Configuration.ConfigurationSettings.AppSettings["Key"];但是现在FrameWork2.0已经明确表示此属性已经过时。
并建议改为ConfigurationManager 或WebConfigurationManager。
并且AppSettings属性是只读的,并不支持修改属性值.但是要想调用ConfigurationManager必须要先在工程里添加system.configuration.dll程序集的引用。
(在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,.net TablePage 下即可找到)添加引用后可以用String str = ConfigurationManager.AppSettings["Key"]来获取对应的值了。
configurationmanager.connectionstrings 用法1. 引言1.1 概述:在开发.NET应用程序时,连接数据库是非常常见的需求。
然而,每次连接数据库都需要手动编写连接字符串会十分繁琐且容易出错。
为了简化这一过程,Microsoft提供了一个名为"Configuration Manager ConnectionStrings"的工具,可以帮助我们更方便地管理和获取连接字符串。
1.2 文章结构:本文将介绍"Configuration Manager ConnectionStrings"的用法,并详细解析配置文件中的ConnectionStrings节点。
然后我们将学习如何使用Configuration Manager来获取配置文件中定义的连接字符串。
最后,在结论部分对所学内容进行总结。
1.3 目的:本文旨在帮助读者理解和掌握"Configuration Manager ConnectionStrings"工具的基本用法,以及如何利用它简化连接字符串的管理和获取过程。
通过阅读本文,读者将能够更加高效地处理数据库连接相关的操作,并提升开发效率和代码质量。
2. Configuration Manager ConnectionStrings 用法Configuration Manager 是一个强大的.NET框架工具,可以帮助我们管理和访问应用程序的配置信息。
其中一个常用的功能是连接字符串(ConnectionStrings)的使用。
在这一部分,我们将详细介绍如何使用Configuration Manager 来处理连接字符串。
连接字符串是应用程序与数据库或其他外部资源建立连接时所需的配置信息。
通过ConnectionStrings 节点,我们可以将这些配置信息统一存储在配置文件中,并在需要时轻松地获取它们。
要使用Configuration Manager 处理连接字符串,首先需要引入System.Configuration 命名空间。
configurationmanager.connectionstrings 用法-回复ConfigurationManager.ConnectionStrings 是一个C中的类,用于访问配置文件中的连接字符串。
在这篇文章中,我将详细介绍ConfigurationManager.ConnectionStrings 的用法。
ConfigurationManager 是C 中的一个类,它提供了访问应用程序配置文件的方法。
应用程序配置文件是一个XML 文件,用于存储应用程序的配置信息。
通过ConfigurationManager,我们可以轻松地访问和修改配置文件中的数据。
ConnectionStrings 是一个ConfigurationManager 中的属性,它用于访问配置文件中的连接字符串。
连接字符串是用于连接到数据库或其他外部资源的字符串,它包含了连接所需的所有信息,如服务器地址、用户名、密码等。
下面是使用ConfigurationManager.ConnectionStrings 的一步一步指南:第一步:添加引用在使用ConfigurationManager.ConnectionStrings 之前,我们需要在项目中添加对System.Configuration 程序集的引用。
这可以通过在Visual Studio 中右键单击项目,然后选择“添加”->“引用”来完成。
在弹出的对话框中,找到并选中System.Configuration 程序集,然后点击“确定”按钮。
第二步:打开配置文件在访问配置文件中的连接字符串之前,我们首先需要打开配置文件。
配置文件的名称通常是App.config 或Web.config,它位于项目的根目录下。
你可以通过在Visual Studio 中双击这个文件来打开它。
第三步:添加连接字符串在配置文件中,连接字符串被包含在ConnectionStrings 元素中。
类库项目读取应用配置文件信息的方法English:One approach for a class library project to read application configuration file information is to utilize the ConfigurationManager class in .NET. This class provides access to configuration files for the application. By using the ConfigurationManager class, the class library can access the settings and connection strings defined in the application's configuration file. The library can use the property to read key-value pairs from the <appSettings> section, and the property to access connection strings from the <connectionStrings> section. This allows the class library to retrieve important configuration settings and connection information required for its functionality.中文翻译:类库项目读取应用配置文件信息的一种方法是利用.NET中的ConfigurationManager类。
该类提供了对应用程序配置文件的访问。
通过使用ConfigurationManager类,类库可以访问应用程序配置文件中定义的设置和连接字符串。
使用ConfigurationManager类读写配置文件
使用ConfigurationManager类读写配置文件app.config,以下为代码:
view plaincopy to clipboard print?
using System;
using System.Configuration;
static class Program
{
static void Main()
{
showConfig();
UpdateAppSettings();
showConfig();
Console.ReadKey(true);
}
private static void showConfig()
{
string = ConfigurationManager.AppSettings["Directory"];
Console.WriteLine("AppSetting配置节Path key的value为:" + dir + "\n");
}
/// <summary>
/// UpdateAppSettings
/// </summary>
public static void UpdateAppSettings()
{
// Get the configuration file.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine("config.FIlePath: " + config.FilePath + "\n");
config.AppSettings.Settings["Directory"].Value = "tset";
// Save the configuration file.
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}
using System;
using System.Configuration;
static class Program
{
static void Main()
{
showConfig();
UpdateAppSettings();
showConfig();
Console.ReadKey(true);
}
private static void showConfig()
{
string = ConfigurationManager.AppSettings["Directory"];
Console.WriteLine("AppSetting配置节Path key的value为:" + dir + "\n");
}
/// <summary>
/// UpdateAppSettings
/// </summary>
public static void UpdateAppSettings()
{
// Get the configuration file.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine("config.FIlePath: " + config.FilePath + "\n");
config.AppSettings.Settings["Directory"].Value = "tset";
// Save the configuration file.
config.AppSettings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");
}
app.config内容:
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Directory" value="C:\Documents and Settings"/>
</appSettings>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Directory" value="C:\Documents and Settings"/>
</appSettings>
</configuration>
代码结果:app.config只能作为初始化的定义,工程生成后运行程序集名称.exe 修改生成后的程序集名称.exe.Config文件
一开始调试时看到控制结果是想要的结果,但看app.config配置文件内容没变(vs2008 F5调试模式下是修改程序集名称.vshost.exe.config配置文件)还以为是代码有问题,网上搜,也有人碰过到此现像,原来是自己没有理解到MSDN的说明。
(还是有文化差异啊)
如:Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine("config.FIlePath: " + config.FilePath + "\n");
查看config.filePath值,即了解明白了。
4.0的类库:/en-us/library/ms134265(v=VS.100).aspx
注意:此类是.net2.0后新增。
必须要先在工程里添加system.configuration.dll程序集的引用。
(在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,.net->组件名称->下即可找到)
添加引用后可以使用System.Configuration空间下的ConfigurationManager类.
引用资源:
/node/258
/KB/cs/SystemConfiguration.aspx
/interboy/archive/2007/04/22/722894.html 使用ConfigurationManager类读写web.config
/blog/static/32082592009813111946229/ 多个示例代码实现
本文来自CSDN博客,转载请标明出处:file:///H:/___Study___/使用ConfigurationManager 类%20读写配置文件%20-.htm。