C # text file searches for a specific word and deletes the entire line of text containing that word

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

+6
source share
3 answers

The easiest way is to rewrite the entire file without the line (s) containing the word. You can use LINQ to do this:

 var oldLines = System.IO.File.ReadAllLines(path); var newLines = oldLines.Where(line => !line.Contains(wordToDelete)); System.IO.File.WriteAllLines(path, newLines); 

If you want to delete all lines containing word (and not just a sequence of characters), you need to split the line into ' ' :

 var newLines = oldLines.Select(line => new { Line = line, Words = line.Split(' ') }) .Where(lineInfo => !lineInfo.Words.Contains(wordToDelete)) .Select(lineInfo => lineInfo.Line); 
+14
source

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); 
+4
source

The code:

"using System.Linq;" not required.

Write your own extension method IsNotAnyOf(,) (put it in a static class) and call the method (i.e. it is called) from .Where(n => n.IsNotAnyOf(...))...(); . For-loop will return false if the condition is met, if not the method will return true:

 static void aMethod() { string[] wordsToDelete = { "aa", "bb" }; string[] Lines = System.IO.File.ReadAllLines(TextFilePath) .Where(n => n.IsNotAnyOf(wordsToDelete)).ToArray(); IO.File.WriteAllLines(TextFilePath, Lines); } static private bool IsNotAnyOf(this string n, string[] wordsToDelete) { for (int ct = 0; ct < wordsToDelete.Length; ct++) if (n == wordsToDelete[ct]) return false; return true; } 
+1
source

Source: https://habr.com/ru/post/914456/


All Articles