2012-08-09 95 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 *?。*?