I have a problem: how can I delete a line from a text file in C#?
I have a problem: how can I delete a line from a text file in C#?
For very large files I'd do 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");
Update I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using LINQ and deferred execution
var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme");
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(fileName);
File.Move(tempFile, fileName);
The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.
A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.
File.WriteAllLines(fileName,
File.ReadLines(fileName).Where(l => l != "removeme").ToList());
Note that The .ToList is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded.
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.
File.ReadAllLines)List<string> then remove the line)File.WriteAllLines) - potentially convert the List<string> into a string array again using ToArrayThat means you have to know that you've got enough memory though. An alternative:
TextReader/TextWriter, e.g. with File.OpenText and File.CreateText)TextReader.ReadLine) - if you don't want to delete it, write it to the output file (TextWriter.WriteLine)using statements for both, this will happen automatically)I'd very simply:
I realize it's been a long time, however this helped me so I wanted to improve on it. The answer from Leonhard was very useful for me. However, If your Text file is really huge like mine, StringBuilder will give an Out-Of-Memory Error. So instead I used it like this. Creates a new file and writes in it. You can then delete the first file if you like. Notice that Line variable determines until which line the file will be deleted. You can modify it to specify the interval of lines you want to delete.
void File_DeleteLine(int Line, string Path, string newPath)
{
StreamReader reader = new StreamReader(Path);
StreamWriter writer = new StreamWriter(newPath);
int Countup = 0;
while (!reader.EndOfStream)
{
Countup++;
if (Countup > Line)
{
writer.WriteLine(reader.ReadLine());
}
else
{
reader.ReadLine();
}
}
}
string fileIN = @"C:\myTextFile.txt";
string fileOUT = @"C:\myTextFile_Out.txt";
if (File.Exists(fileIN))
{
string[] data = File.ReadAllLines(fileIN);
foreach (string line in data)
if (!line.Equals("my line to remove"))
File.AppendAllText(fileOUT, line);
File.Delete(fileIN);
File.Move(fileOUT, fileIN);
}
Remove a block of code from multiple files
To expand on @Markus Olsson's answer, I needed to remove a block of code from multiple files. I had problems with Swedish characters in a core project, so I needed to install System.Text.CodePagesEncodingProvider nuget package and use System.Text.Encoding.GetEncoding(1252) instead of System.Text.Encoding.UTF8.
public static void Main(string[] args)
{
try
{
var dir = @"C:\Test";
//Get all html and htm files
var files = DirSearch(dir);
foreach (var file in files)
{
RmCode(file);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
private static void RmCode(string file)
{
string tempFile = Path.GetTempFileName();
using (var sr = new StreamReader(file, Encoding.UTF8))
using (var sw = new StreamWriter(new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8))
{
string line;
var startOfBadCode = "<div>";
var endOfBadCode = "</div>";
var deleteLine = false;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(startOfBadCode))
{
deleteLine = true;
}
if (!deleteLine)
{
sw.WriteLine(line);
}
if (line.Contains(endOfBadCode))
{
deleteLine = false;
}
}
}
File.Delete(file);
File.Move(tempFile, file);
}
private static List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files.Where(s => s.EndsWith(".htm") || s.EndsWith(".html")).ToList();
}