-1

Possible Duplicate:
Efficient way to delete a line from a text file

I have a multithreaded app, and a text file containing a list of proxy servers. If a proxy is not valid, I need to delete it from text file.

How to do it, if I don't want to lose speed of app?

For example I need to delete 62.109.29.58:8085 from

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
Community
  • 1
  • 1
  • 1
    - use the search, there are [plenty](http://tinyurl.com/d7pwxnp) of similar questions on SO. – Tim Schmelter Dec 13 '12 at 19:42
  • I would not close this question just yet, because OP appears to be interested in dealing with tiny files; the duplicate question talks about processing larger files efficiently. – Sergey Kalinichenko Dec 13 '12 at 19:53
  • 1
    I'm disappointed to note that nobody's keyed on to the multi-threaded nature of the question and performance concerns. It's not just that the file needs to be filtered, it needs to be threadsafe and reasonably performant. – Reacher Gilt Dec 13 '12 at 20:23

2 Answers2

4

Since your file appears small, you can read the whole file in, remove the line that you must remove, and then write the file back:

File.WriteAllLines("myfile.txt"
,   File.ReadLines("myfile.txt").Where(s => s != "62.109.29.58:8085").ToList()
);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
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);  
        }
    }
}
Caleb Keith
  • 816
  • 4
  • 10