c#,Winform应用程序 - 搜索特定行并将其替换为其他行

时间:2015-04-14 12:49:11

标签: c# search replace line

我有一个带有按钮的小型winform应用程序,单击该按钮时,我想搜索特定单词的文本文件(file.txt),并用其他内容替换找到它的整行。

假设我的文本文件是:

ohad yes no
box cat dog
etc...

我想搜索ohad,一旦发现它将“ohad yes no”替换为新行“是的,我做了”

所以txt文件将是:

yes I did it
box cat dog
etc...

到目前为止,这是我的代码:

string lineX;
               StringBuilder sb = new StringBuilder();                     
               using (System.IO.StreamReader file = new     System.IO.StreamReader(textBox20.Text))
                {
                    while ((lineX = file.ReadLine()) != null)
                    {
                        if (lineX.Contains("SRV"))
                        {

                            sb.AppendLine(lineX.ToString());
                        }
                    }
                }
                StreamReader streamReader;
                streamReader = File.OpenText(textBox20.Text);
                string contents = streamReader.ReadToEnd();
                streamReader.Close();
                StreamWriter streamWriter = File.CreateText(textBox20.Text);
                streamWriter.Write(contents.Replace(sb.ToString(), textBox26.Text + textBox29.Text + textBox30.Text + textBox27.Text + textBox28.Text));
                streamWriter.Close(); 

提前谢谢大家 辖

2 个答案:

答案 0 :(得分:1)

试试这个:

// Read file into a string array (NOTE: You should check if exists first!)
string[] Lines = File.ReadAllLines(textBox20.Text);

for(int i=0;i<Lines.Length;i++) { 
    if(Lines[i].Contains("SRV")) {
       Lines[i] = "New value for line"; 
       // if you only want to replace one line, uncomment the next row:
       // break;
    }
}

// Write array back to file
File.WriteAllLines(textBox20.Text, Lines);

答案 1 :(得分:0)

对于一个初学者来说,如何按照这些评论进行整理。

var s = @"
ohad yes no
box cat dog
";

//split string into array

//go through each item in array
//check if it contains "ohad"
//if so, replace that line with my text

//convert array to string