目前我正在写一个库,使读写INI文件变得简单,我已经让读者工作并编写了关键字和值不存在但我无法轻易更新值的问题,我尝试过多种方法来替换字符串但没有一个是实用和程序要求的旧值如何替换文件中的未知字符串?
这是我从这里尝试一个例子:Regular Expression to replace unknown value in text file - c# and asp.net
Regex rgx = new Regex(@"SQL-SERVER-VERSION="".*?""");
string result = rgx.Replace(input, replacement);
但每次我修改的代码替换值,它最终取代该键会因此导致应用程序在下次尝试读取文件时发生错误。
这里是代码我使用目前:
private string wholedata;
private void UpdateKey(string key, string path, string newval)
{
try
{
using (StreamReader s = new StreamReader(File.Open(path, FileMode.Open)))
{
wholedata = s.ReadToEnd();
Regex rgx = new Regex(key + ".*?");
string result = rgx.Replace(wholedata, newval);
MessageBox.Show(result);
}
using (StreamWriter s = new StreamWriter(File.Open(path, FileMode.OpenOrCreate)))
{
s.Write(wholedata);
}
}
catch (Exception e)
{
}
}
为什么重写什么系统已经知道该怎么做前提的
.*?
?看看这个项目:http://www.codeproject.com/Articles/1966/An-INI-file-handling-class-using-C。无论如何,你正在写旧的价值(wholedata),而不是新的价值(结果)。这可能是根本原因。 – 2012-07-31 12:21:06感谢您的快速回复!我希望能够实现我自己的版本,虽然看到这个我可能只是建立它的顶部,谢谢! :) – 2012-07-31 12:23:22
我的第一个问题是,如果它是未知的 - 你怎么知道它是在那里:-) – 2012-07-31 12:23:50