2012-08-09 54 views
2

我有一個特定格式的文本文件。首先是一個標識符,後跟三個空格和一個冒號。然後是這個標識符的值。用C#搜索並替換文本文件中的值

ID1 :Value1 
ID2 :Value2 
ID3 :Value3 

我需要做的是搜索例如爲ID2 :並用新值NewValue2替換Value2。有什麼辦法可以做到這一點?我需要解析的文件不會很大。最大的將是150條左右的線路。

+0

你應該指定類型的值1,值2 ...整數,字符串? – ocanal 2012-08-09 13:21:01

回答

3

如果文件不是很大,你可以做一個File.ReadAllLines獲得所有行的集合,然後替換你正在尋找這樣

using System.IO; 
using System.Linq; 
using System.Collections.Generic; 

List<string> lines = new List<string>(File.ReadAllLines("file")); 
int lineIndex = lines.FindIndex(line => line.StartsWith("ID2 :")); 
if (lineIndex != -1) 
{ 
    lines[lineIndex] = "ID2 :NewValue2"; 
    File.WriteAllLines("file", lines); 
} 
+0

唯一的問題是如果他上面的數據不準確,並且每個新的「ID」值都不在新行中。 – Phil 2012-08-09 13:24:50

+0

然後他可以去File.ReadAllText並解析一個大字符串,如果他說這是一個問題,我會把這個例子提出來;另一方面..他確實說過這個文件是150 *行* – mtijn 2012-08-09 13:26:55

+0

是的,每個ID肯定在一個新行中。 – 2012-08-09 14:46:33

1

按說線,對於任何文本搜索和替換,我會建議一些正則表達式的工作,但如果這是你所做的一切,那真是矯枉過正。

我只是打開原始文件和臨時文件;每次讀取原始的一行,並檢查每一行的「ID2:」;如果你發現它,把你的替換字符串寫入臨時文件,否則,只寫你讀的東西。當您用完源代碼時,關閉兩者,刪除原始文件,並將臨時文件重命名爲原始文件。

-1

您可以使用regexes來實現這一點。

Regex re = new Regex(@"^ID\d+ :Value(\d+)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); 

List<string> lines = File.ReadAllLines("mytextfile"); 
foreach (string line in lines) { 
    string replaced = re.Replace(target, processMatch); 
    //Now do what you going to do with the value 
} 

string processMatch(Match m) 
{ 
    var number = m.Groups[1]; 
    return String.Format("ID{0} :NewValue{0}", number); 
} 
0

像這樣的東西應該工作。這很簡單,不是最有效的事情,但對於小文件,這將是蠻好的:

private void setValue(string filePath, string key, string value) 
{ 
    string[] lines= File.ReadAllLines(filePath); 
    for(int x = 0; x < lines.Length; x++) 
    { 
     string[] fields = lines[x].Split(':'); 
     if (fields[0].TrimEnd() == key) 
     { 
      lines[x] = fields[0] + ':' + value; 
      File.WriteAllLines(lines); 
      break; 
     } 
    } 
} 
+0

沒有linq的很好的例子 – mtijn 2012-08-09 13:31:39

4

這裏有一個簡單的解決方案,它還會自動創建源文件的備份。

替換項存儲在Dictionary對象中。他們鍵入該線路的ID,例如, 'ID2'並且該值是需要的字符串替換。只需使用Add()根據需要添加更多。

StreamWriter writer = null; 
Dictionary<string, string> replacements = new Dictionary<string, string>(); 
replacements.Add("ID2", "NewValue2"); 
// ... further replacement entries ... 

using (writer = File.CreateText("output.txt")) 
{ 
    foreach (string line in File.ReadLines("input.txt")) 
    { 
     bool replacementMade = false; 
     foreach (var replacement in replacements) 
     { 
      if (line.StartsWith(replacement.Key)) 
      { 
       writer.WriteLine(string.Format("{0} :{1}", 
        replacement.Key, replacement.Value)); 
       replacementMade = true; 
       break; 
      } 
     } 
     if (!replacementMade) 
     { 
      writer.WriteLine(line); 
     } 
    } 
} 

File.Replace("output.txt", "input.txt", "input.bak"); 

你要自己與路徑源,目標和備份文件替換input.txtoutput.txtinput.bak

+0

問題是,我不知道「Value2」的價值。換句話說:我需要替換「ID2:」後面的所有內容。 – 2012-08-09 14:47:46

+0

@RobertStrauch - 請參閱上面的更新示例。 – 2012-08-09 15:16:39

0

您可以使用正則表達式,並做到在3行代碼

string text = File.ReadAllText("sourcefile.txt"); 
text = Regex.Replace(text, @"(?i)(?<=^id2\s*?:\s*?)\w*?(?=\s*?$)", "NewValue2", 
        RegexOptions.Multiline); 
File.WriteAllText("outputfile.txt", text); 

在正則表達式,(我?)(< =^ID2 \ S *:???\ S *)\ W *?(?= \ s *?$)表示在:前後找到以id2開頭的任何空格,並將下列字符串(任何字母數字字符,不包括標點符號)全部替換爲'直到行結束。如果要包含標點符號,則請替換\ w *?。*?