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)));
Daniel Iankov
Read all of the contents of a file into a string then just run
string output = null;
try {
output = Regex.Replace(input, @"^\s*$", "", RegexOptions.Multiline);
} catch (Exception e) {
}
Other similar options can be found in How to remove empty lines from a formatted string?
来源:https://stackoverflow.com/questions/6480058/remove-blank-lines-in-a-text-file