使用ConfigurationManager类 读写配置文件
Config文件的使用:通过程序修改Config文件
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多个配置文件读取问题
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路径进行解析,帮助读者更好地理解和使用该工具。
二、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 用法-回复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)操作实践及代码详注
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
.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类还是很⽅便的。
2024年WPF入门教程详解适合新手上路
提供一系列命令或选项,用 允许用户通过拖动滑块来选
户通过点击进行选择。
择一个范围内的值。
自定义控件开发流程示例
01
02
03
04
05
设计控件外观和功 创建自定义控件类 实现控件逻辑 能
定义控件样式和模 在应用程序中使用
板
自定义…
确定控件将要呈现的外观以 及提供的功能。
继承自现有控件或基类,添 加自定义属性和方法。
实现多语言界面。
资源文件访问
使用`ResourceManager`类可以方便 地访问和管理嵌入在应用程序中的资 源文件。
本地化工具
使用Visual Studio的本地化工具可以 方便地创建、编辑和管理多语言资源 文件。
配置文件读写和设置保存策略
配置文件类型 配置文件读写 设置保存策略 加密和解密
WPF支持多种配置文件类型,如XML文件、INI文件、注册表等, 可以根据需要选择合适的类型。
WPF动画系统概述
1 2
动画类型 WPF提供了多种动画类型,包括线性动画、关键 帧动画和路径动画等,可以满足不同的动画需求。
故事板
故事板是WPF动画的核心概念,它用于组织和控 制动画的播放,可以实现复杂的动画效果。
3
依赖属性 WPF动画通过改变元素的依赖属性值来实现动画 效果,这使得动画的应用非常灵活。
04 数据绑定与 MVVM模式实践
数据绑定原理及实现方式探讨
数据绑定定义
数据绑定是一种将UI元素与数据 源相关联的技术,当数据源发生 变化时,UI元素会自动更新以反
映新的数据。
实现方式
WPF中数据绑定可以通过XAML或 代码后置方式实现,绑定目标可以 是控件的属性、集合或方法等。
使用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>。
2024版WPF入门基础
目录
• 入门概述 • 基础概念解析 • 核心编程技术探讨 • 界面设计与优化实践 • 数据交互与存储方案研究 • 调试、测试与发布流程梳理
01
入门概述
Chapter
WPF定义与特点
定义
WPF(Windows Presentation Foundation)是 微软推出的基于Windows Vista的用户界面框架, 用于替代传统的WinForms等技术。
使用`StreamReader`和 `StreamWriter`类进行文本文件的 读取和写入操作,支持编码设置和 逐行处理。
二进制文件读写
使用`FileStream`类进行二进制文 件的读写操作,可以配合 `BinaryReader`和`BinaryWriter` 类简化数据读写过程。
配置文件读写
使用`ConfigurationManager`类 读取应用程序的配置文件(如
考虑换肤过程中对性能和 内存的影响。
性能优化策略分享
01
减少不必要的布局更新和重绘操作。
02 使用虚拟化技术提高大数据量下的界面性 能。
03
优化数据绑定和事件处理机制以降低内存 占用。
04
考虑使用异步编程模型提高界面响应速度。
05
数据交互与存储方案研究
Chapter
本地文件读写操作指南
文本文件读写
集成测试
将各个模块组合起来进行测试,确保模块之间的接口和交互能够正 常工作。
性能测试
模拟多用户并发访问场景,测试系统的性能指标,如响应时间、吞 吐量等。
版本控制和持续集成工具
Git
分布式版本控制系统,支持分支 管理、代码合并等功能,便于团 队协作开发。
configurationmanager.connectionstrings 用法 -回复
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,开发人员可以方便地获取和使用连接字符串,从而简化应用程序的开发和部署过程。
在本文中,我们将详细介绍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配置文件
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#读取和写入配置文件
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)
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_用法
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 用法-回复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类,类库可以访问应用程序配置文件中定义的设置和连接字符串。
C#类库DLL配置文件
C#类库DLL配置⽂件C#类库DLL配置⽂件在.NET⾥⾯,类库项⽬是没有相应的配置⽂件的,但有时候写⼀些公共的类库DLL,⼜希望有配置⽂件来进⾏配置,以适应需求变化。
还是⽼话,微软既然不提供,咱⾃⼰来写个吧。
在类库项⽬中创建ConfigurationManager类.使⽤.NET framework 4.0,在web,windows,window service 中均进⾏过测试。
使⽤时需将配置⽂件命名为 dll名字.config 并放置在引⽤类库DLL项⽬的debug或者release ⽂件夹下。
SetConnectionStrings(string keyNameValue, string value) { SetNameAndValue("connectionStrings",应value值的设置 /// </summary> /// <param name="sectionTag">对应节点</param> /// <paramname="KeyOrName">对应key或者name</param> /// <param name="keyNameValue">key或者name的值</param> /// <param name="valueOrConnectionString">对应key或者name 的value值</param> privatestatic void SetNameAndValue(string sectionTag, string KeyOrName, string keyNameValue, stringvalueOrConnectionString) { string assemblyPath =Assembly.GetExecutingAssembly().GetName().CodeBase; //获取运⾏项⽬当然DLL的路径 assemblyPath= assemblyPath.Remove(0, 8);//去除路径前缀 string configUrl = assemblyPath + ".config"; //添加.config后缀,得到配置⽂件路径 try { XmlDocument cfgDoc = new XmlDocument();cfgDoc.Load(configUrl); XmlNodeList nodes = cfgDoc.GetElementsByTagName(sectionTag);foreach (XmlNode node in nodes) { foreach (XmlNode childNode in node.ChildNodes){ XmlAttributeCollection attributes = childNode.Attributes; if(attributes.GetNamedItem(KeyOrName).InnerText == keyNameValue) {attributes.GetNamedItem("value").InnerText = valueOrConnectionString; } } }cfgDoc.Save(configUrl); } catch (FileNotFoundException es) { throw es; } }/// <summary> /// 根据节点名,⼦节点名,获取指定值 /// </summary> /// <paramname="sectionTag">对应节点</param> /// <param name="KeyOrName">key或者name</param> ///<param name="valueOrConnectionString">key或者name的值</param> /// <returns>key或者name对应value值</returns> private static Hashtable GetNameAndValue(string sectionTag, string KeyOrName,string valueOrConnectionString) { Hashtable settings = new Hashtable(5);//初始化Hashtablestring assemblyPath = Assembly.GetExecutingAssembly().GetName().CodeBase;//获取运⾏项⽬当然DLL的路径 assemblyPath = assemblyPath.Remove(0, 8); //去除前缀 string configUrl = assemblyPath +".config"; //添加 .config 后缀,得到配置⽂件路径 XmlDocument cfgDoc = new XmlDocument();FileStream fs = null; try { fs = new FileStream(configUrl, FileMode.Open,FileAccess.Read); cfgDoc.Load(new XmlTextReader(fs)); XmlNodeList nodes =cfgDoc.GetElementsByTagName(sectionTag); foreach (XmlNode node in nodes) {foreach (XmlNode childNode in node.ChildNodes) { XmlAttributeCollection attributes =childNode.Attributes; settings.Add(attributes[KeyOrName].Value,attributes[valueOrConnectionString].Value); } } } catch (FileNotFoundExceptiones) { throw es; } finally { if (fs != null) { fs.Close();} } return settings; } }}。
ASP.NETCore系列:读取配置文件
Core系列:读取配置⽂件1. 控制台应⽤ 新建⼀个控制台应⽤,添加两个Package:Install-Package Microsoft.Extensions.ConfigurationInstall-Package Microsoft.Extensions.Configuration.Json1.1 单个配置⽂件 创建配置⽂件appsettings.json:{"Data": "10000","ConnectionStrings": {"DevContext": "开发库","ProdContext": "⽣产库"}} 读取配置⽂件:using System;using System.IO;using Microsoft.Extensions.Configuration;namespace Libing.Core.ConsoleApp{class Program{static void Main(string[] args){var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");var config = builder.Build();Console.WriteLine(config["Data"]); // 配置键Console.WriteLine(config.GetSection("ConnectionStrings:DevContext").Value); // 分层键}}} 通过ConfigurationBuilder对象来创建ConfigurationRoot对象,进⾏读取配置⽂件。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
使用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。