2012-04-29 104 views

回答

14

最简单的方法是重写整个文件,而不用包含该单词的行。您可以使用LINQ为:

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

如果你只是想删除包含(字符不仅序列)的所有行,你需要' '分割线:

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

啊是的,这是完全有道理的,我刚刚在我的代码中使用它,它已经工作:) Thankyou非常多! – user1364063 2012-04-29 12:03:28

4

您可以轻松地做到这一点,而不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); 
+0

@mMd Kamruzzaman Pallob我怎么能为多个词..这对我完全工作..但对于一个单词..我需要寻找三个字..我怎么能做到这一点..谢谢 – 2014-11-03 18:31:51

1

代码:

“using System.Linq;”是必须的。

写自己的扩展方法IsNotAnyOf(,)(把它放在一个静态类).Where(n => n.IsNotAnyOf(...))...();的调用方法(即它被称为) for循环,如果条件得到满足将返回false,如果不是该方法将返回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; 
} 
相关问题