目前我正在寫一個庫,使讀寫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