C# text file search for specific word and delete whole line of text that contains that word
c#, search, text-files
Solution
The easiest is to rewrite the whole file without the line(s) that contain the word. You can use `LINQ` for that:
var oldLines = System.IO.File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains(wordToDelete));
System.IO.File.WriteAllLines(path, newLines);
If you only want to delete all lines that contain the word(not only the sequence of characters), you need to split the line by `' '`:
var newLines = oldLines.Select(line => new {
Line = line,
Words = line.Split(' ')
})
.Where(lineInfo => !lineInfo.Words.Contains(wordToDelete))
.Select(lineInfo => lineInfo.Line);
Problem
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.