App.config配置文件的读写,我想实现自定义属性的增减(我只实现了写,但读就是报错)

mqmmx 2006-06-19 11:41:44
以下是我定义的类代码,但只要我加入自定义属性读明就会错,因为没有为这个属性加入定义好的类,但怎么得到已知的文件中自定义属性的名称和值呢

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace ReadAndWriteConfig
{
// Define a custom section.
// The CustomSection type alows to define a custom section
// programmatically.
public sealed class ConfigDataClass :
ConfigurationSection
{
#region 实例化Property的各属性struct
[Serializable]
public struct structProperty
{
private Type _type;
private string _value;
private ConfigurationPropertyOptions _cpo;

public structProperty(Type type,
string defalutValue,
ConfigurationPropertyOptions confPropOption)
{
_type = type;
_value = defalutValue;
_cpo = confPropOption;
}

public structProperty(Type type, string defalutValue)
:
this(type, defalutValue, ConfigurationPropertyOptions.None)
{ }

public structProperty(string defalutValue)
:
this(typeof(string), defalutValue, ConfigurationPropertyOptions.None)
{ }

public Type PropertyType
{
get { return _type; }
}

public string PropertyValue
{
get { return _value; }
}

public ConfigurationPropertyOptions ConfPropOpt
{
get { return _cpo; }
}
}
#endregion

// ConfigurationProperty's fullname
private const string sProperty = "System.Configuration.ConfigurationProperty";

// The collection (property bag) that conatains
// the section properties.
private ConfigurationPropertyCollection _Properties;

//必须静态否则自定义属性无法保存
private static Hashtable _PropertyCollect = new Hashtable();

// The MasUsers property.
private ConfigurationProperty _MaxUsers =
new ConfigurationProperty("maxUsers",
typeof(long), (long)1000,
ConfigurationPropertyOptions.None);

// The MaxIdleTime property.
private ConfigurationProperty _MaxIdleTime =
new ConfigurationProperty("maxIdleTime",
typeof(TimeSpan), TimeSpan.FromMinutes(5),
ConfigurationPropertyOptions.IsRequired);

// CustomSection constructor.
public ConfigDataClass()
{
// Property initialization
_Properties =
new ConfigurationPropertyCollection();

PropertyToCollect();
}

public void AddProperty(string PropertyName, string PropertyValue)
{
AddProperty(PropertyName, new structProperty(PropertyValue));
}

public void AddProperty(string PropertyName, string PropertyValue,
Type PropertyType)
{
AddProperty(PropertyName, new structProperty(PropertyType, PropertyValue));
}

public void AddProperty(string PropertyName, string PropertyValue,
Type PropertyType,
ConfigurationPropertyOptions ptc)
{
AddProperty(PropertyName, new structProperty(PropertyType, PropertyValue, ptc));
}

public void AddProperty(string PropertyName, structProperty PropertyValue)
{
if (_PropertyCollect.ContainsKey(PropertyName) == true)
{
_PropertyCollect.Remove(PropertyName);
}
_PropertyCollect.Add(PropertyName, PropertyValue);
}

/// <summary>
/// 将属性加入属性集合
/// </summary>
private void PropertyToCollect()
{
ConfigurationProperty p;
structProperty sp;

_Properties.Clear();

foreach (DictionaryEntry d in _PropertyCollect)
{
sp = (structProperty)d.Value;

object[] o = new object[4];
o[0] = d.Key.ToString();
o[1] = sp.PropertyType;
o[2] = sp.PropertyValue;
o[3] = sp.ConfPropOpt;

p = (ConfigurationProperty)Assembly.Load(Assembly.GetAssembly(typeof(ConfigurationProperty)).FullName).CreateInstance(sProperty,
false,
BindingFlags.Default,
null,
o,
null,
null);

_Properties.Add(p);
}

_Properties.Add(_MaxIdleTime);
_Properties.Add(_MaxUsers);
}

// This is a key customization.
// It returns the initialized property bag.
protected override ConfigurationPropertyCollection Properties
{
get
{
return _Properties;
}
}

// Customizes the use of CustomSection
// by setting _ReadOnly to false.
// Remember you must use it along with ThrowIfReadOnly.
protected override object GetRuntimeObject()
{
return base.GetRuntimeObject();
}

[LongValidator(MinValue = 1, MaxValue = 1000000,
ExcludeRange = false)]
public long MaxUsers
{
get
{
return (long)this["maxUsers"];
}
set
{
this["maxUsers"] = value;
}
}

[TimeSpanValidator(MinValueString = "0:0:30",
MaxValueString = "5:00:0",
ExcludeRange = false)]
public TimeSpan MaxIdleTime
{
get
{
return (TimeSpan)this["maxIdleTime"];
}
set
{
this["maxIdleTime"] = value;
}
}
}
}
...全文
516 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
mqmmx 2006-06-19
  • 打赏
  • 举报
回复
楼上是不是说EnterpriseLibrary
这是我下了2.0版的但代码太多,没时间看,你有没有简单的例子啊
长江支流 2006-06-19
  • 打赏
  • 举报
回复
读写配置文件有一个配置文件管理类,你直接用就行了。
或者你写一个简单的XML,直接用DataSet打开即可,可以直接操作并保存。
mqmmx 2006-06-19
  • 打赏
  • 举报
回复
错了上面ReadXml改为ReadAppSettings


如有其它好方法也希望提出,后天结贴
mqmmx 2006-06-19
  • 打赏
  • 举报
回复
看了MSDN2005后,原来配置文件可以用AppSettingsSection 来写
下面是我新改的类
namespace ReadAndWriteConfig
{
/// <summary>
/// 配置文件类
/// </summary>
public class ConfigDataClass
{
private string _fileName = "";

//存放配置信息
private Hashtable ht;

public string FileName
{
set { _fileName = value; }
}

public ConfigDataClass()
{
ht = new Hashtable();
}

public void ReadXml(string readFileName)
{
this.FileName = readFileName;
ReadXml();
}

//读取XML文件的方法
public void ReadAppSettings()
{
try
{
ExeConfigurationFileMap f = new ExeConfigurationFileMap();
f.ExeConfigFilename = _fileName;

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

AppSettingsSection ass = config.GetSection("appSettings") as AppSettingsSection;

int appCount = ass.Settings.AllKeys.Length;

string[] kv = ass.Settings.AllKeys;

ht.Clear();

for (int i = 0; i < appCount; i++)
{
ht.Add(kv[i], ass.Settings[kv[i]].Value);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

public string GetKeyValue(string key)
{
if (ht.ContainsKey(key) == true)
return ht[key].ToString();

return "";
}

public void SetKeyValue(string key, string keyvalue)
{
//查一下是否存在,存在就干掉
if (ht.ContainsKey(key) == true)
{
ht.Remove(key);
}

//加入新值
ht.Add(key, keyvalue);
}

//写入信息到XML文件的方法
public void WriteAppSettings()
{
ExeConfigurationFileMap f = new ExeConfigurationFileMap();
f.ExeConfigFilename = _fileName;

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

config.AppSettings.Settings.Clear();
foreach (DictionaryEntry d in ht)
{
config.AppSettings.Settings.Add(d.Key.ToString(), d.Value.ToString());
}

config.Save(ConfigurationSaveMode.Full);
}
}
}
mqmmx 2006-06-19
  • 打赏
  • 举报
回复
多谢楼上的代码,其它还有没有关于继承ConfigurationSection类写的写配置文件方法吗?
qyfjl 2006-06-19
  • 打赏
  • 举报
回复
给个例子给你看一下:
//读取XML文件的方法
public static string ReadXml(string key)
{
string returnValue="";
try
{
//得到这个KEY的值
returnValue=System.Configuration .ConfigurationSettings .AppSettings[key];
}
catch(Exception e)
{
MessageBox.Show (e.Message .ToString ());
}
return returnValue;
}
//写入信息到XML文件的方法
public static void WriteXml(string key,string key_value)
{
//实例化一个XML文档
XmlDocument dc=new XmlDocument ();
dc.Load (filePath);//加载XML配置文件


//查找XML文件的节点
XmlNode node=dc.SelectSingleNode ("//appSettings");
if(node==null)
{
throw new InvalidOperationException ("appSettings段在配置文件中没有找到.");
}
try
{
//从节点中得到KEY这个元素
XmlElement elem=(XmlElement)node.SelectSingleNode (string.Format ("//add[@key='{0}']",key));
if(elem!=null)
{
//设置属性value的值
elem.SetAttribute ("value",key_value);
}
else
{
//创建一个新的元素
elem=dc.CreateElement ("add");
elem.SetAttribute ("key",key);
elem.SetAttribute ("value",key_value);
node.AppendChild (elem);
}
//保存更改的配置文件.
dc.Save (filePath);
}
catch
{
throw;
}

}
mqmmx 2006-06-19
  • 打赏
  • 举报
回复
可能是我问得不够明白,我再写一下。我的类可以如下这样用

ConfigDataClass configData;

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "c:\\test.config";

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

config.Sections.Remove("ConfigTest");

configData= new ConfigDataClass();
//TestString是配置文件的属性名称,zz为TestString属性的值,我在类的內部用反射实现了属性类的定义
configData.AddProperty("TestString", "zz");
config.Sections.Add("ConfigTest", configData);
configData.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);



但用反射实现的属性如何在我读配置文件时知道文件中的哪个属性是需要內部反射实现,哪个是不需要反射实现的啊!!!

to:quou2002(曲欧)
连接打不开
mybilly2016 2006-06-19
  • 打赏
  • 举报
回复
App.Config应该是第一次运行程序的时候,程序读取并缓存了吧,你后面的修改只有等到重启程序才有用,建议用其他的配置文件来实现你的功能
quou2002 2006-06-19
  • 打赏
  • 举报
回复
可以简单看看Alois Kraus的小工具:
http://geekswithblogs.net/akraus1/archive/2006/03/05/71481.aspx
的源代码,这是一个配置EntLib的工具,你可以只看其修改App配置的部分。。。



==== 我的邮箱:quou2002@tom.com
~~~~ 我的Blog:http://blog.csdn.net/quou2002

110,530

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧