Hello,
I have a problem: how can I delete a line from a text file in C#?
Hello,
I have a problem: how can I delete a line from a text file in C#?
Read the file, remove the line in memory and put the contents back to the file (overwriting). If the file is large you might want to read it line for line, and creating a temp file, later replacing the original one.
I agree with John Saunders, this isn't really C# specific. However, to answer your question: you basically need to rewrite the file. There are two ways you can do this.
List<string>
then remove the line)List<string>
into a string array again using ToArray
That means you have to know that you've got enough memory though. An alternative:
using
statements for both, this will happen automatically)For large files I'd to something like this
string tempFile = Path.GetTempFileName();
using(var sr = new StreamReader("file.txt"))
{
using(var sw = new StreamWriter(tempFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
if(line != "removeme")
sw.WriteLine(line);
}
}
}
File.Delete("file.txt");
File.Move(tempFile, "file.txt");
I'd very simply: