c# File.ReadAllLines 不读取空行
c# File.ReadAllLines doesn't read blank lines
我正在使用 C# 读取一些 txt 文档和 writing/deleting 其中的一些行
我必须阅读一个文本文档,删除其中的一些行,然后将其再次保存在同一路径中。
它工作得很好,直到我意识到它不读取空行或者当新行中只有 space :(.
这是我的文本文件结构:
-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
****here comes the empty line****
这是我的代码:
List<string> myLines = File.ReadAllLines(path).ToList();
if (myLines.Count > 5)
{
for(int i = 7; i >= 5; i--)
{
myLines.RemoveAt(i);
}
File.WriteAllLines(path, myLines.ToArray());
}
所以我不知道为什么当我 运行 File.ReadAllLines 会给我 7 行(忽略空白行)当然在我删除文件中的内容后,空白行是还在。
注意:我正在处理超过 10 万个文件,无论哪种方式,我都会手动删除该特定行。
你能帮我解决这个问题并删除那个空行吗?谢谢。
这是一些代码:
var f = @"-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
-Name2";
File.WriteAllText(@"C:\temp\a.txt", f);
var f2 = File.ReadAllLines(@"C:\temp\a.txt").ToList();
f2.RemoveAt(7);
f2.RemoveAt(6);
f2.RemoveAt(5);
File.WriteAllLines(@"C:\temp\b.txt", f2);
打开 c:\temp 中的两个结果文件 a.txt 和 b.txt(确保你有一个 c:\temp)- a 有空行,b 没有中间空行或 address2/3
..但请注意 b 在末尾有一个空行,因为 File.WriteAllLines
将以 CRLF 结束最后一行(在我的示例中为 Name2)。
如果这就是您所说的 about/you 不想要的,请考虑其他事情,也许:
File.WriteAllText(@"C:\temp\b.txt", string.Join(Environment.NewLine, f2));
我正在使用 C# 读取一些 txt 文档和 writing/deleting 其中的一些行 我必须阅读一个文本文档,删除其中的一些行,然后将其再次保存在同一路径中。 它工作得很好,直到我意识到它不读取空行或者当新行中只有 space :(.
这是我的文本文件结构:
-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
****here comes the empty line****
这是我的代码:
List<string> myLines = File.ReadAllLines(path).ToList();
if (myLines.Count > 5)
{
for(int i = 7; i >= 5; i--)
{
myLines.RemoveAt(i);
}
File.WriteAllLines(path, myLines.ToArray());
}
所以我不知道为什么当我 运行 File.ReadAllLines 会给我 7 行(忽略空白行)当然在我删除文件中的内容后,空白行是还在。
注意:我正在处理超过 10 万个文件,无论哪种方式,我都会手动删除该特定行。
你能帮我解决这个问题并删除那个空行吗?谢谢。
这是一些代码:
var f = @"-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
-Name2";
File.WriteAllText(@"C:\temp\a.txt", f);
var f2 = File.ReadAllLines(@"C:\temp\a.txt").ToList();
f2.RemoveAt(7);
f2.RemoveAt(6);
f2.RemoveAt(5);
File.WriteAllLines(@"C:\temp\b.txt", f2);
打开 c:\temp 中的两个结果文件 a.txt 和 b.txt(确保你有一个 c:\temp)- a 有空行,b 没有中间空行或 address2/3
..但请注意 b 在末尾有一个空行,因为 File.WriteAllLines
将以 CRLF 结束最后一行(在我的示例中为 Name2)。
如果这就是您所说的 about/you 不想要的,请考虑其他事情,也许:
File.WriteAllText(@"C:\temp\b.txt", string.Join(Environment.NewLine, f2));