使用StreamReader在文件中查找正则表达式并使用StreamWriter覆盖它

时间:2013-04-19 17:55:35

标签: c# regex streamreader streamwriter

我正在使用StreamReader阅读文本文件并使用Regex.Match查找特定信息,现在当我找到它时,我想用Regex.Replace替换它,我想把这个替换写回文件。

这是我文件中的文字:

/// 
/// <Command Name="Press_Button"  Comment="Press button" Security="Security1">
/// 
/// <Command Name="Create_Button"  Comment="Create button" Security="Security3">
/// ... lots of other Commands 

现在我需要找到:Security =“Security3”&gt;在Create_Button命令中,将其更改为Security =“Security2”&gt;并将其写回文件

do { 
    // read line by line 
    string ReadLine = InfoStreamReader.ReadLine();

    if (ReadLine.Contains("<Command Name"))
     {
         // now I need to find Security1, replace it with Security2 and write back to the file
     }
   }
while (!InfoStreamReader.EndOfStream);

欢迎任何想法......

编辑: 好的调用是从tnw逐行读取和写入文件。需要一个例子。

1 个答案:

答案 0 :(得分:3)

我会做更像这样的事情。你不能像在那里那样直接写入文件中的一行。

这不使用正则表达式,但完成同样的事情。

var fileContents = System.IO.File.ReadAllText(@"<File Path>");

fileContents = fileContents.Replace("Security1", "Security2"); 

System.IO.File.WriteAllText(@"<File Path>", fileContents);

直接从这里拉出来:c# replace string within file

或者,您可以循环播放并逐行读取文件,并逐行将其写入新文件。对于每一行,您可以检查Security1,替换它,然后将其写入新文件。

例如:

StringBuilder newFile = new StringBuilder();

string temp = "";

string[] file = File.ReadAllLines(@"<File Path>");

foreach (string line in file)
{
    if (line.Contains("Security1"))
    {

    temp = line.Replace("Security1", "Security2");

    newFile.Append(temp + "\r\n");

    continue;

    }

newFile.Append(line + "\r\n");

}

File.WriteAllText(@"<File Path>", newFile.ToString());

来源:how to edit a line from a text file using c#