简体   繁体   中英

c# , Winform application -search for specific line and replace it with other line

I have a small winform app with a button, which, when clicked, I want to search a text file ( file.txt ) for a specific word and replace the entire line on which it was found by something else.

Let's say my text file is:

ohad yes no
box cat dog
etc...

I want to search for ohad and once find it replace the line "ohad yes no" to new line "yes I did it"

so the txt file will be:

yes I did it
box cat dog
etc...

This is my code so far:

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(); 

Thanks you all in advance
Ohad

Try this:

// 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);

for a starter, how about following these comments i put together.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM