StreamReader reader = new StreamReader("randomTextFile.txt");
string line = "";
while (line != null)
{
line = reader.ReadLine();
if (line != null)
{
Console.WriteLine(line);
}
}
reader.Close();
Console.ReadLine();
在上面的代码中,while 语句内有一个 if 语句,尽管它们指定了相同的内容 (line != null)
。如果我删除所说的 if 语句,则会在 txt 文件内容后面添加一个新行(而不是“11037”,控制台将显示“11037”+一个空行)。
最佳答案
while
-loop退出条件仅在调用时才会检查,因此在每次迭代开始时检查,而不是每次在其范围内检查。
MSND: the test of the while expression takes place before each execution of the loop
你可以使用这个循环:
string line;
using (var reader = new StreamReader("randomTextFile.txt"))
{
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
您还应该在每个实现 IDisposable
的对象上使用如上所示的 using
语句。这样可以确保非托管资源得到处置。
根据Console.WriteLine
特定问题,即使值为null
,为什么它会写入新行,那就是 documented :
If value is null, only the line terminator is written to the standard output stream.
关于C#-为什么此 if 语句会删除 StreamReader 输出上的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199518/