How can you remove blank lines from a text file in C#?
If file is small:
var lines = File.ReadAllLines(fileName).Where(arg => !string.IsNullOrWhiteSpace(arg));
File.WriteAllLines(fileName, lines);
If file is huge:
var tempFileName = Path.GetTempFileName();
try
{
using (var streamReader = new StreamReader(inptuFileName))
using (var streamWriter = new StreamWriter(tempFileName))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
streamWriter.WriteLine(line);
}
}
File.Copy(tempFileName, inptuFileName, true);
}
finally
{
File.Delete(tempFileName);
}
File.WriteAllLines(path, File.ReadAllLines(path).Where(l => !string.IsNullOrWhiteSpace(l)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With