简体   繁体   中英

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.

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

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

Code:

"using System.Linq;" is required.

Write your own extension method IsNotAnyOf(,) (put it in a static class) and call the method (ie it is called) from .Where(n => n.IsNotAnyOf(...))...(); The 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;
}

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

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