Remove blank lines in a text file

喜欢而已 提交于 2019-12-03 16:58:08

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!