2017-04-16 105 views
0

我裏面:如何刪除文本文件中的行保存一個字符串變量

String yourName = "bob"; 

現在我想從文本文件中刪除鮑勃。我將如何做到這一點?

using (StreamReader reader = new StreamReader("C:\\input")) 
         { 
          using (StreamWriter writer = new StreamWriter("C:\\output")) 
          { 
           while ((line = reader.ReadLine()) != null) 
           { 
            if (String.Compare(line, yourName) == 0) 
             continue; 

            writer.WriteLine(line); 
           } 
          } 
         } 

我查看過這個網站以及YouTube,但沒有任何內容。

這可能嗎?

回答

0

這是可能的。您需要循環查看當前行是否包含您的string
這裏是這樣做的一個例子:

string yourName = "bob"; 
string oldLine; 
string newLine = null; 
StreamReader sr = File.OpenText("C:\\input"); 
while ((oldLine = sr.ReadLine()) != null){ 
    if (!oldLine.Contains(yourName)) newLine += oldLine + Environment.NewLine; 
} 
sr.Close(); 
File.WriteAllText("C:\\output", newLine); 

注:這將刪除所有含字bob
也行,如果你想寫入同一個文件,只需用輸入文件而不是output

File.WriteAllText("C:\\output", newLine); 

我希望有幫助!

+0

豎起大拇指:)謝謝。你能否看看我的另一個問題,5天內沒有回答。請致電 –

+0

@PearlPrincess沒問題!很高興我能幫上忙 :) – NullDev

1

你應該使用替換法:

using (StreamReader reader = new StreamReader("C:\\input")) 
        { 
         using (StreamWriter writer = new StreamWriter("C:\\output")) 
         { 
          while ((line = reader.ReadLine()) != null) 
          { 
           // if (String.Compare(line, yourName) == 0) 
           // continue; 

           writer.WriteLine(line.Replace(yourName, ""); 
          } 
         } 
        } 

如果名字是在該行的話,那就可以用「」代替,你已經刪除了它。如果名稱不在該行中,則替換方法返回整個不變的行。

Show this link for more informations.

0

是否的line值必須正好等於yourName字符串?

如果你的目標是包含YOURNAME

if (line.Contains(yourName)) continue; 

應該足夠了線,然後。

但是,如果你正在尋找省略是完全一樣yourName線,然後

if (line?.ToLowerCase() == yourName?.ToLowerCase()) continue; 

應該夠了。

相關問題