我个人很喜欢我在网上找到的这段代码。这是一种在属性文件中读/写的个人化方式。使用的
public class Properties
{
private Dictionary<String, String> list;
private String filename;
public Properties(String file)
{
reload(file);
}
public String get(String field, String defValue)
{
return (get(field) == null) ? (defValue) : (get(field));
}
public String get(String field)
{
return (list.ContainsKey(field))?(list[field]):(null);
}
public void set(String field, Object value)
{
field = this.trimUnwantedChars(field);
value = this.trimUnwantedChars(value);
if (!list.ContainsKey(field))
list.Add(field, value.ToString());
else
list[field] = value.ToString();
}
public string trimUnwantedChars(string toTrim)
{
toTrim = toTrim.Replace(";", string.Empty);
toTrim = toTrim.Replace("#", string.Empty);
toTrim = toTrim.Replace("'", string.Empty);
toTrim = toTrim.Replace("=", string.Empty);
return toTrim;
}
public void Save()
{
Save(this.filename);
}
public void Save(String filename)
{
this.filename = filename;
if (!System.IO.File.Exists(filename))
System.IO.File.Create(filename);
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
foreach(String prop in list.Keys.ToArray())
if (!String.IsNullOrWhiteSpace(list[prop]))
file.WriteLine(prop + "=" + list[prop]);
file.Close();
}
public void reload()
{
reload(this.filename);
}
public void reload(String filename)
{
this.filename = filename;
list = new Dictionary<String, String>();
if (System.IO.File.Exists(filename))
loadFromFile(filename);
else
System.IO.File.Create(filename);
}
private void loadFromFile(String file)
{
foreach (String line in System.IO.File.ReadAllLines(file))
{
if ((!String.IsNullOrEmpty(line)) &&
(!line.StartsWith(";")) &&
(!line.StartsWith("#")) &&
(!line.StartsWith("'")) &&
(line.Contains('=')))
{
int index = line.IndexOf('=');
String key = line.Substring(0, index).Trim();
String value = line.Substring(index + 1).Trim();
if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
(value.StartsWith("'") && value.EndsWith("'")))
{
value = value.Substring(1, value.Length - 2);
}
try
{
//ignore duplicates
list.Add(key, value);
}
catch { }
}
}
}
}
实施例:
//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()
有一个DUP:http://stackoverflow.com/questions/485659/can-c-load-and-parse-a-properties-file-equivilant- to-java-properties-class – skaffman 2010-01-30 22:32:59
这些看起来类似: http://stackoverflow.com/questions/485659/can-c-load-and-parse-a-properties-file-equivilant-to-java-properties-class http://stackoverflow.com/questions/217902/reading-writing-ini-file-in-c – ziya 2010-01-30 22:38:14
根据作者的意图,这可能不是一个重复。 (尽管看起来作者并不热衷于XML)Andrew Hare已经提供了唯一可能的答案,如果这不是重复的话。 – 2010-01-30 22:38:56