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);
}