使用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类读写配置文件
使用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。