如何从文本文件中删除字符串?

时间:2012-12-13 19:40:08

标签: c#

  

可能重复:
  Efficient way to delete a line from a text file

我有一个多线程应用程序,以及一个包含代理服务器列表的文本文件。如果代理无效,我需要从文本文件中删除它。

如果我不想失去app的速度怎么办?

例如,我需要删除62.109.29.58:8085

62.109.7.22:8085
62.109.0.35:8085
92.63.106.111:8085
78.24.216.163:8085
92.63.97.156:8085
82.146.56.156:8085
62.109.29.58:8085
78.24.220.173:8085
78.24.220.111:8085
92.63.106.124:8085

2 个答案:

答案 0 :(得分:4)

由于您的文件显得很小,您可以读取整个文件,删除必须删除的行,然后将文件写回:

File.WriteAllLines("myfile.txt"
,   File.ReadLines("myfile.txt").Where(s => s != "62.109.29.58:8085").ToList()
);

答案 1 :(得分:0)

string[] lines = System.IO.File.ReadAllLines("filename.txt");
for (int i = 0; i < lines.Length; i++)
{
    string line = lines[i];
    if (line == "what you are looking for")
       lines[i] = "";
}

string[] newLines = lines.Where(str => !string.IsNullOrEmpty(str)).ToArray();
using (Stream stream = File.OpenWrite("filename.txt"))
{
    using (StreamWriter sw = new StreamWriter(stream))
    {
        foreach (string line in newLines)
        {
            sw.WriteLine(line);  
        }
    }
}