我正在使用StreamReader读取文件。这些文件有时在其他行之间有空行。中间的空行数可以是任意数。让StreamReader跳过所有空行直到读取非空行的最佳方法是什么?
我有一个在while循环中调用的函数:
/// <summary>
/// Moves the stream to the next non-empty line, and returns it.
/// </summary>
/// <param name="srFile"></param>
private string GetNextLine(StreamReader srFile)
{
string line = srFile.ReadLine();
if (String.IsNullOrWhiteSpace(line))
GetNextLine(srFile);
return line;
}
一切似乎都很好,但是由于某些原因,这是行不通的。每当行不为空时,返回行的确会命中,但是由于某种原因,会进行更递归的“ GetNextLine()”调用。谁能看到我在做什么错,或提供解决方案?
您忘了返回递归调用的结果:
private string GetNextLine(StreamReader srFile)
{
string line = srFile.ReadLine();
if (String.IsNullOrWhiteSpace(line))
return GetNextLine(srFile); //here
return line;
}