Winform 读取 指定\另一个\其他\任意 配置文件

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = @"F:\App1.config"; ;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string connstr = config.ConnectionStrings.ConnectionStrings["connStr"].ConnectionString;
            MessageBox.Show(connstr);
            string key = config.AppSettings.Settings["key"].Value;
            MessageBox.Show(key);

How To Read/Write Another App.Config File
To open another App.Config file you need to create an instance of ExeConfigurationFileMap.
The purpose of this class is not that obvious but we can use it to open
another file. Once you have learned this little trick the rest is easy.
Here is a little example that does open an file by specifying it‘s
name.

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

fileMap.ExeConfigFilename = @"ConfigTest.exe.config";  // relative path names possible

// Open another config file

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

// read/write from it as usual

ConfigurationSection mySection = config.GetSection("mySection");

config.SectionGroups.Clear(); // make changes to it

config.Save(ConfigurationSaveMode.Full);  // Save changes


The Microsoft Enterprise Library way
has a shorthand utility class for this. It is the
FileConfigurationSource which does hide those strange things. Tom Hollander has a nice post explaining this already so I will not repeat the same at my blog.

Another Way to read/write configuration values

A
more advanced way to store our settings is to create our own
ConfigurationSection. This makes our configuration values
distinguishable from other configuration values inside the App.config
file. It is a little more complicated since you have to write your own
class which content is de/serialized to the App.config file. I am going
to show you at first the config file and explain then what code you need
to write to read/save these settings to your application configuration
file.

App.Config  (Taken from the Enterprise Library Configuration Migration QuickStart Sample)

<configuration>

<configSections>

<section name="EditorSettings" type="ConfigurationMigrationQuickStart.EditorFontData,
ConfigurationMigrationQuickStart, Version=1.1.0.0, Culture=neutral,
PublicKeyToken=null" />

</configSections>

<EditorSettings name="Verdana" size="24" style="2" />

</configuration>

Most App.config files which contain config data have a <configSections> element where many <section> are defined. The name attribute of an section (in this example "EditorSettings") tells the config system that the class ConfigurationMigrationQuickStart.EditorFontData is responsible for the ser/deserialization of the node <EditorSettings>. The EditorFontData class derives from the ConfigurationSection class and uses the ConfigurationProperty attribute to create a mapping between the properties to de/serialize and the attribute names in names in the App.Config file.

using System.Text;

using System.Configuration;

public class EditorFontData : ConfigurationSection

{

public EditorFontData()

{

}

[ConfigurationProperty("name")]

public string Name

{

get { return (string)this["name"]; }

set{ this["name"] = value; }

}

[ConfigurationProperty("size")]

public float Size

{

get{ return (float)this["size"]; }

set{ this["size"] = value; }

}

[ConfigurationProperty("style")]

public int Style

{

get { return (int)this["style"]; }

set{ this["style"] = value; }

}

}

To access an EditorFontData instance with values from your config file you only need to call

EditorFontData configData = ConfigurationManager.GetSection("EditorSettings") as EditorFontData;

Please note that the System.Configuration.ConfigurationManager
returns only objects with read only properties. Subsequent calls to
GetSection use the cached instance inside the ConfigurationManager. This
constraint requires you to create every time a new instance of you e.g.
EditorFontData object if you want to write to the App.config file. You
even cannot add an object with the same name twice to the
System.Configuration.Configuration object. Now comes the fun part: To
edit an existing App.config file you have to remove your config object
and then add a new object instance to the Configuration object. Only
then the Save will succeed.

EditorFontData configData = new EditorFontData();

configData.Name = "Arial";

configData.Size = 20;

configData.Style = 2;

// Write the new configuration data to the XML file

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.Sections.Remove("EditorSettings");

config.Sections.Add("EditorSettings", configData);

config.Save();

To get your hands on the System.Configuration.Configuration
object you have to open your App.Config file. The .NET config mechanism
supports setting inheritance from the Machine.config from which all
settings are inherited. Next comes the App.Config file which is selected
by the ConfigurationUserLevel.None file.

http://geekswithblogs.net/akraus1/articles/64871.aspx

时间: 2024-10-14 04:15:48

Winform 读取 指定\另一个\其他\任意 配置文件的相关文章

C#读取指定路径下的Config配置文件

ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = @"F:\App1.config"; ; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); string connstr = config.Connectio

实现快速读写配置文件的内容,可以用于读取*.exe.config文件或者Web.Config文件的内容,或者可以读取指定文件的配置项.

形如: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microso

Winform读取文档。然后创建,奇数行保存一个文档,偶数行保存一个文档

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using System.Text.RegularExpressions; namespace TextModify

java web实现读取指定盘符下的图像(二)

之前写了一篇文章是关于如何读取指定盘符下的图片,虽然功能可以实现,但是使用的是I/O流的方式,效率不高.现在发现还有一个更好的办法,使用也更加的方便. 我们知道,当我们的图片是放在tomcat下webapps的应用目录下,使用src="127.0.1:8080/xx/123.png"这种方式就能访问图片.那么如果我们能将指定文件夹作为tomcat的工作空间,这样就可以直接访问图片了. 我们只需在tomcat的conf->server.xml的host中添加: <Contex

WinForm 读取Excel 数据显示到窗体中

最近教学中,需要用到WinForm 读取Excel数据,于是就做了一个简单的,废话不多说,直接codding... 1 //读取Excel的帮助类 2 class SqExcellHelper 3 { 4 public static DataTable GetData(string tablename) 5 { 6 DataTable dtEmp = new DataTable(tablename); 7 OleDbConnection con = new OleDbConnection();

winform 读取TXT文件 放在Label中

<span style="font-family: Arial, Helvetica, sans-serif;">#region 读取TXT 文件,放到Label中</span> private void ReadTXT(Label lab) { string strTxtAll = "";//定义一个string变量 string abc = "C:\Users\xxb\Desktop\1.txt";//路径 FileS

Python--通过索引excel表将文件进行文件夹分类的脚本+读取指定目录下所有文件名的脚本

1.通过索引excel表将文件进行文件夹分类的脚本,此脚本由于将ip和id对应并生成对应id的文件夹将文件进行分类,也可以任意规定表格内容,通过vul_sc_ip.txt和xlsx文件进行索引. # -*- coding:utf8 -*- import sys import os import pandas as pd import shutil import stat def find(path,ip): # open the excel file df = pd.read_excel(pat

读取指定路径的Excel内容到DataTable中

1 /// <summary> 2 /// 读取指定路径的Excel内容到DataTable中 3 /// </summary> 4 /// <param name="path"></param> 5 /// <returns></returns> 6 public DataTable ImportToDataSet(string path) 7 { 8 string strConn = "Provide

Matlab学习:读取指定文件夹及其五级子文件夹内的文件

OpenCV2.4.X版本提供了三个函数来读取指定目录内的文件,它们分别是: (1)GetListFiles:读取指定目录内所有文件,不包含子目录: (2)GetListFilesR:读取指定目录及其子目录(仅一级子目录)内所有文件: (3)GetListFolders:读取指定目录内所有目录,不包含文件: 然而,Matlab中并没有对应的函数,有人可能会说dir不就可以吗,但dir返回的值还进行一些处理我们才能用的,如移除返值中包含的父目录及当前目录.这里我就写了一段代码来读取指定目录及其子目