Remove blank lines in a text file

旧巷老猫 提交于 2019-12-05 00:08:28

问题


How can you remove blank lines from a text file in C#?


回答1:


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



回答2:


File.WriteAllLines(path, File.ReadAllLines(path).Where(l => !string.IsNullOrWhiteSpace(l)));



回答3:


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

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