WinForm中使用XML文件存储用户配置及操作本地Config配置文件
大家都开发winform程序时候会大量用到配置App.config作为保持用户设置的基本信息,比如记住用户名,这样的弊端就是每个人一些个性化的设置每次更新程序的时候会被覆盖。
故将配置文件分两大类:
公用系统配置文件(App.config)和私用配置文件(xml文件).
一、公用系统配置文件(App.config)的读写操作。本文参考:http://www.cnblogs.com/dotnet_way/archive/2010/07/26/config_file.html#2902913
读写.NET应用程序配置文件 1.读取配置文件 有如下的配置文件 <xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ApplicationTitle" value="DevAsp Application Configuration Sample" />
<add key="ApplicationHeaderText" value="DevAsp" />
</appSettings> <connectionStrings>
<add name="ConnectionString" connectionString="user id=DevAsp;data source=Northwind;persist security info=True;initial catalog=Comments;password=abc" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration> 读取ApplicationTitle,代码如下: ConfigurationSettings.AppSettings["ApplicationTitle"]; 读取连接字符串的代码: ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); 2.写入配置文件 假设有如下配置文件: <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Test1" value="My value 1" />
<add key="Test2" value="Another value 2" />
</appSettings>
</configuration> 写配置文件的代码: using System;
using System.Xml;
using System.Configuration;
using System.Reflection;
//... public class ConfigSettings
{
private ConfigSettings() {} public static string ReadSetting(string key)
{
//不建议通过这种自带的方式进行读取;如果手动修改了配置文件,则不会第二次读取的时候,依旧是内存中的值。可以通过XML方式进行读取。
//return ConfigurationSettings.AppSettings[key];
// load config document for current assembly
XmlDocument doc = loadConfigDocument(); // retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings"); if (node == null)
throw new InvalidOperationException("appSettings section not found in config file."); try
{
// select the 'add' element that contains the key
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key)); if (elem != null)
{
// add value for key
return elem.GetAttribute("value");
} }
catch
{
throw;
} return ""
} public static void WriteSetting(string key, string value)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument(); // retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings"); if (node == null)
throw new InvalidOperationException("appSettings section not found in config file."); try
{
// select the 'add' element that contains the key
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key)); if (elem != null)
{
// add value for key
elem.SetAttribute("value", value);
}
else
{
// key was not found so create the 'add' element
// and set it's key/value attributes
elem = doc.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
doc.Save(getConfigFilePath());
}
catch
{
throw;
}
} public static void RemoveSetting(string key)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument(); // retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings"); try
{
if (node == null)
throw new InvalidOperationException("appSettings section not found in config file.");
else
{
// remove 'add' element with coresponding key
node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
doc.Save(getConfigFilePath());
}
}
catch (NullReferenceException e)
{
throw new Exception(string.Format("The key {0} does not exist.", key), e);
}
} private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
} private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
} 例如: // read the Test1 value from the config file
string test1 = ConfigSettings.ReadSetting("Test1"); // write a new value for the Test1 setting
ConfigSettings.WriteSetting("Test1", "This is my new value"); // remove the Test1 setting from the config file
ConfigSettings.RemoveSetting("Test1");
二、私用配置文件(xml文件).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Data.Linq; namespace EmailSystem.Utility.UserConfigSettings
{
[Serializable]
public class UserProfie
{
/// <summary>
///
/// </summary>
public string Key { get; set; } /// <summary>
///
/// </summary>
public string Value { get; set; } } /// <summary>
///
/// </summary>
public class UserConfigXML
{
public static readonly UserConfigXML Instance = new UserConfigXML();
private string filePath;
private List<UserProfie> userProfies = new List<UserProfie>();
private UserConfigXML()
{
filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UserConfig.xml");
LoadUserConfigXML();
} /// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string ReadSetting(string key)
{
var up = userProfies.FirstOrDefault(m => m.Key == key);
if (up != null)
return userProfies.FirstOrDefault(m => m.Key == key).Value;
else
return string.Empty;
} /// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void WriteSetting(string key, string value)
{
var us = userProfies.FirstOrDefault(m => m.Key == key);
if (us != null)
userProfies.Remove(us);
userProfies.Add(new UserProfie { Key = key, Value = value });
SaveUserConfigXML(); } /// <summary>
///
/// </summary>
/// <param name="key"></param>
public void RemoveSetting(string key)
{
var us = userProfies.FirstOrDefault(m => m.Key == key);
if (us != null)
{
userProfies.Remove(us);
SaveUserConfigXML();
}
} /// <summary>
///
/// </summary>
private void SaveUserConfigXML()
{
try
{
#region [XML序列化方式]
//<?xml version="1.0"?>
//<ArrayOfUserProfie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
// <UserProfie>
// <Key>key1</Key>
// <Value>1</Value>
// </UserProfie>
// <UserProfie>
// <Key>key2</Key>
// <Value>2</Value>
// </UserProfie>
//</ArrayOfUserProfie>
//XmlSerializer serializer = new XmlSerializer(typeof(List<UserProfie>));
//using (FileStream stream = new FileStream(filePath, FileMode.Create))
//{
// serializer.Serialize(stream, userProfies);
//}
#endregion #region [Linq to XML方式]
//<AppSettings>
// <add key="key1" value="1" />
// <add key="key1" value="1" />
//</AppSettings>
var domLinq = new XElement("AppSettings",
from c in userProfies
select new XElement("add",
new XAttribute("key", c.Key),
new XAttribute("value", c.Value))
); domLinq.Save(filePath);
#endregion
}
catch (Exception ex)
{ }
} /// <summary>
///
/// </summary>
private void LoadUserConfigXML()
{
if (File.Exists(filePath))
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(List<UserProfie>));
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
userProfies = (List<UserProfie>)xs.Deserialize(fs);
}
#region [Linq to XML方式]
//XDocument xdoc = XDocument.Load(filePath);
//var userConfiLst = from a in xdoc.Descendants("AppSettings").Elements("add")
// select new UserConfig
// {
// Key = a.Attribute("key").Value,
// Value = a.Attribute("value").Value,
// };
//this.userProfies = userConfiLst.ToList();
#endregion
}
catch (Exception ex)
{ }
}
}
} public class TestClass
{
public void TestUserConfig()
{
UserConfigXML.Instance.WriteSetting("key1", "1");
UserConfigXML.Instance.WriteSetting("key2", "2");
var key = UserConfigXML.Instance.ReadSetting("key1");
UserConfigXML.Instance.ReadSetting("key2");
UserConfigXML.Instance.RemoveSetting("key2");
}
}
} XML序列化格式:
<?xml version="1.0"?> <ArrayOfUserProfie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <UserProfie> <Key>key1</Key> <Value>1</Value> </UserProfie> <UserProfie> <Key>key2</Key> <Value>2</Value> </UserProfie> </ArrayOfUserProfie>
Linq to xml 格式:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<AppSettings>
<add key="key1" value="1" />
<add key="key1" value="1" />
</AppSettings>
三、改进写法:采用微软自带写法,读取本地其他config文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO; namespace EmailSystem.Utility.UserConfigManage
{
public class UserLocalConfigSettings
{
/// <summary>
///
/// </summary>
public static readonly UserLocalConfigSettings Instance = new UserLocalConfigSettings(); /// <summary>
///
/// </summary>
private string filePath = string.Empty; /// <summary>
///
/// </summary>
private UserLocalConfigSettings()
{
filePath = GetConfigFilePath();
} /// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string ReadSetting(string key)
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = filePath;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
if (appConf.AppSettings.Settings[key] != null)
return appConf.AppSettings.Settings[key].Value;
else
return string.Empty;
} /// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void WriteSetting(string key, string value)
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = filePath;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
if (appConf.AppSettings.Settings[key] != null)
appConf.AppSettings.Settings.Remove(key);
appConf.AppSettings.Settings.Add(key, value);
appConf.Save(ConfigurationSaveMode.Modified);
} /// <summary>
///
/// </summary>
/// <param name="key"></param>
public void RemoveSetting(string key)
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = filePath;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
if (appConf.AppSettings.Settings[key] != null)
{
appConf.AppSettings.Settings.Remove(key);
appConf.Save(ConfigurationSaveMode.Modified);
}
} /// <summary>
///
/// </summary>
/// <returns></returns>
private string GetConfigFilePath()
{
return Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UserConfigSettings.config");
} } public class TestUserLocalConfigSettings
{
public void TestUserLocalConfigSettingsMethod()
{ string str1 = UserLocalConfigSettings.Instance.ReadSetting("FailedEmailTryCount");
// write a new value for the Test1 setting
UserLocalConfigSettings.Instance.WriteSetting("Test1", "This is my new value"); // remove the Test1 setting from the config file
UserLocalConfigSettings.Instance.RemoveSetting("Test1"); UserLocalConfigSettings.Instance.WriteSetting("EmailPath", "This is my new value");
}
}
}
补充:打开任意的配置文件
一、读取默认的App.config文件
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
如果采用根据指定路径名称读取的话,会调用时候会出现目录下产生一个副本文件
ConfigurationManager.OpenExeConfiguration("E:\App.config");
这个方法会在这个目录下产生一个副本文件(E:\App.config.config),
二、读取自定义本地文件的Config文件
ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
读语句: String str = ConfigurationManager.AppSettings["DemoKey"].Value;
写语句: Configuration config = ConfigurationManager.OpenExeConfiguration("E:\db.config");
config.AppSettings.Settings["DemoKey"].Value = "DemoValue";
config.Save(); 配置文件内容格式:(db.config) <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DemoKey" value="*" />
</appSettings>
</configuration> 以上是网上转载,我仔细测试了一下,发现这段代码会有一个小问题(其实网上的人也说到了), ConfigurationManager.OpenExeConfiguration("E:\db.config"); 这个方法会在这个目录下产生一个副本文件(E:\db.config.config), 而代码真正操作的文件却不是db.config,而是程序自动创建的db.config.config文件,所以很苦恼,若删除原文件,则又会提示报错, 在这里我做了一点稍微的改动就可以达要我们想要的目的,(不生成文件副本,直接操作此文件,且更新操作也是操作此文件): //先实例化一个ExeConfigurationFileMap对象,把物理地址赋值到它的 ExeConfigFilename 属性中;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"E:\MySrc\db.config"; //再调用fileMap 实例化 config , 这样,操作的文件就是db.config文件了,也不会产生副本文件
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); //读写操作跟原来一样,不变
String str = ConfigurationManager.AppSettings["DemoKey"];
config.AppSettings.Settings["DemoKey"].Value = "DemoValue"; //写完之后一定要保存,否则不会保存到文件中去的
config.Save();
本文章转载:http://www.cppblog.com/lzyuan1006/archive/2009/12/24/103998.aspx
http://blog.csdn.net/dbzhang800/article/details/7212420
http://www.cnblogs.com/goldpicker/archive/2006/08/25/486675.html
WinForm中使用XML文件存储用户配置及操作本地Config配置文件的更多相关文章
- WinForm中使用XML文件存储用户配置及操作本地Config配置文件(zt)
因项目中采用CS结构读取Web.config文件,故参照一下的连接完成此功能,在此感谢原作者! 原文地址: http://www.cnblogs.com/zfanlong1314/p/3623622. ...
- Winform中对xml文件进行保存时空白节点自动换行问题的解决
场景 Winform中自定义xml配置文件后对节点进行读取与写入: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10053213 ...
- ANT 发布项目中 build.xml 文件的详细配置
xml 代码 <?xml version="1.0" encoding="UTF-8"?> <!-- name:对应工程名字 default: ...
- asp.net 操作INI文件的读写,读写操作本地ini配置文件
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Secu ...
- Maven中pom.xml文件的配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...
- MyEclipse/Eclipse中XML文件的格式化配置
Eclipse中XML文件的格式化配置 MyEclipse: 这一步的配置是使格式化的效果为控件的每个属性配置占一行.进入 Window/Preferences,展开到 XML/XML Resourc ...
- Tomcat中server.xml文件的配置
server.xml文件当中可配置如下信息: 1)配置端口号(如果是正式网站,要把8080改成80)<Connector executor="tomcatThreadPool" ...
- vue中利用.env文件存储全局环境变量,以及配置vue启动和打包命令
目录 1,前言 2,.env文件的作用 3,配置.env文件 4,配置启动命令 5,获取.env中的全局变量 5,实际用处 1,前言 分享一下vue项目中利用.env文件存储全局环境变量,以及利于项目 ...
- 谈谈对XML的理解?说明Web应用中Web.xml文件的作用?
谈谈对XML的理解?说明Web应用中Web.xml文件的作用? 解答:XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard ...
随机推荐
- spring profile 多环境配置管理
本地.测试.开发.产品等不同环境文件配置 现象 如果在开发时进行一些数据库测试,希望链接到一个测试的数据库,以避免对开发数据库的影响. 开发时的某些配置比如log4j日志的级别,和生产环境又有 ...
- sentinel搭建redis集群经验总结
一.protected-mode默认情况下,redis node和sentinel的protected-mode都是yes,在搭建集群时,若想从远程连接redis集群,需要将redis node和se ...
- Python抓取网页中的图片到本地
今天在网上找了个从网页中通过图片URL,抓取图片并保存到本地的例子: #!/usr/bin/env python # -*- coding:utf- -*- # Author: xixihuang # ...
- 51nod 1134 最长递增子序列
题目链接:51nod 1134 最长递增子序列 #include<cstdio> #include<cstring> #include<algorithm> usi ...
- PostgreSQL的时间/日期函数使用 转
http://www.cnblogs.com/mchina/archive/2013/04/15/3010418.html
- 读<jQuery 权威指南>[6]--实用工具函数
官方地址:http://api.jquery.com/category/utilities/ 一.数组和对象操作 1. $.each——遍历 $.each(obj,function(param1,pa ...
- PHP内置函数file_put_content(),将数据写入文件,使用FILE_APPEND 参数进行内容追加
file_put_contents(fileName,data,flags,context) 入参说明: 参数 说明 fileName 要写入数据的文件名 data 要写入的数据.类型可以是 stri ...
- iOS开发UI篇—transframe属性(形变)
iOS开发UI篇—transframe属性(形变) 1. transform属性 在OC中,通过transform属性可以修改对象的平移.缩放比例和旋转角度 常用的创建transform结构体方法分两 ...
- .htaccess设置自定义出错页面
404错误可以这么写 ErrorDocument code error.php 如果是404错误,跳到文件error.php 其他常用错误页面写法(其中404错误有2种写法,上面一种,下面是通用错误定 ...
- BCG界面库下的Windows8 UI界面样式www.webui8.com
BCG界面库下的Windows8 UI界面样式(Metro风格)控件主要有以下一些功能: 规则的大块磁贴 支持完整键盘导航 Tile组 标题(Caption) 标题按钮(Caption buttons ...