i want to remove one line in a txt file after i've gotten the data with StreamReader.WriteLine(). but i cannot get any useful reference for the web. somebody tell me that i can do it with the Repalce() method .but i dont think its efficent. can anyone tell me how to resolve it. thanks!
Asked
Active
Viewed 3,585 times
1 Answers
4
You can't remove something in the middle of a file. You either have to rewrite everything from that point on, or simply rewrite the whole file. And if you are using StreamReader/StreamWriter, then you don't have any access to file position, so your only choice is to rewrite the whole file.
Here is an example method on how to do it.
public static void RemoveLines(Predicate<string> removeFunction,string file){
string line, tempFile = null;
try{
tempFile = Path.GetTempFileName();
using (StreamReader sr = new StreamReader(file))
using (StreamWriter sw = new StreamWriter(tempFile,false,sr.CurrentEncoding))
while ((line = sr.ReadLine()) != null)
if (!removeFunction(line)) sw.WriteLine(line);
File.Delete(file);
File.Move(tempFile, file);
}finally{
if(tempFile != null && File.Exists(tempFile))
File.Delete(tempFile);
}
}
Used like this
RemoveLines(line=>line.Length==10,"test.txt")
it removes all the lines with a length of 10 characters, and uses a temp file to minimize the risks involved. Of course, if you want something shorter you could do something like this.
File.WriteAllLines(fileName,File.ReadAllLines(fileName).Where(line => line.Length != 10))
Requires more working memory, and you should probably do the tempfile/move trick to hedge against a computer crash causing a corrupt file. But it is code that is compact and easy to understand.

Marcus Andrén
- 965
- 7
- 9