在C#中如何从文本文件中删除空行?
在C#中如何从文本文件中删除空行?
var lines = File.ReadAllLines(fileName).Where(arg => !string.IsNullOrWhiteSpace(arg));
File.WriteAllLines(fileName, lines);
如果文件很大: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);
}
streamReader
,否则只需使用ReadAllLines
方法。 - atconwayFile.WriteAllLines(path, File.ReadAllLines(path).Where(l => !string.IsNullOrWhiteSpace(l)));
string output = null;
try {
output = Regex.Replace(input, @"^\s*$", "", RegexOptions.Multiline);
} catch (Exception e) {
}
其他类似的选项可以在如何从格式化字符串中删除空行?中找到。
string[] text = File.ReadAllLines(path with file name).Where(s => s.Trim() != string.Empty).ToArray();
It will delete that file.
File.Delete(path with file name);
It will create new file as same name and append all the array data into new file
File.WriteAllLines(path with file name, text);
完整代码
string[] text = File.ReadAllLines(LoraWan_Parameter_Check_Tool.Properties.Settings.Default.csv_file_path.ToString()).Where(s => s.Trim() != string.Empty).ToArray();
File.Delete(LoraWan_Parameter_Check_Tool.Properties.Settings.Default.csv_file_path.ToString());
File.WriteAllLines(LoraWan_Parameter_Check_Tool.Properties.Settings.Default.csv_file_path.ToString(), text);
问题已解决