有时我们需要从流中读取行,但仅将特定的字符序列视为换行符(CRLF,但不是 CR 或 LF)。
StreamReader.ReadLine
,如文档所述,将 CRLF、CR 和 LF 视为换行符序列。如果该行可以包含单个 CR(“\r”)或单个 LF(“\n”)作为业务值(value)数据,则这可能是 Not Acceptable 。
需要能够逐行读取流,但由特定字符序列分隔。
最佳答案
这是一个从流中读取行并将其作为字符串返回的方法:
public static string ReadLineWithFixedNewlineDelimeter(StreamReader reader, string delim)
{
if (reader.EndOfStream)
return null;
if (string.IsNullOrEmpty(delim))
{
return reader.ReadToEnd();
}
var sb = new StringBuilder();
var delimCandidatePosition = 0;
while (!reader.EndOfStream && delimCandidatePosition < delim.Length)
{
var c = (char)reader.Read();
if (c == delim[delimCandidatePosition])
{
delimCandidatePosition ++;
}
else
{
delimCandidatePosition = 0;
}
sb.Append(c);
}
return sb.ToString(0, sb.Length - (delimCandidatePosition == delim.Length ? delim.Length : 0));
}
关于c# - 使用 StreamReader.ReadLine 读取具有特定 NewLine 字符序列的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39845388/