Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# text file search for specific word and delete whole line of text that contains that word

Basically I have a text file that I read in and display in a rich text box, which is fine, but I then want to be able to search through the text for a specific word and delete the whole line of text that contains this word. I can search through the text to see if the word exists or not but I cannot figure out how to delete the whole line. Any help would be great.

like image 977
user1364063 Avatar asked Apr 29 '12 11:04

user1364063


2 Answers

We can convert the string to an array of lines, work over it, and convert back:

string[] dados_em_lista = dados_em_txt.Split(
                        new[] { "\r\n", "\r", "\n" },
                        StringSplitOptions.None
                    );

var nova_lista = dados_em_lista.Where(line => !line.Contains(line_to_remove)).ToArray();

dados_em_txt = String.Join("\n", nova_lista);
like image 119
Pedro Reis Avatar answered Nov 04 '22 06:11

Pedro Reis


You can do it easily without LINK

                string search_text = text;
                string old;
                string n="";
                StreamReader sr = File.OpenText(FileName);
                while ((old = sr.ReadLine()) != null)
                {
                    if (!old.Contains(search_text))
                    {
                        n += old+Environment.NewLine;  
                    }
                }
                sr.Close();
                File.WriteAllText(FileName, n);
like image 26
Md Kamruzzaman Sarker Avatar answered Nov 04 '22 06:11

Md Kamruzzaman Sarker