【问题标题】:Read lines with specific NewLine char sequence with StreamReader.ReadLine使用 StreamReader.ReadLine 读取具有特定 NewLine 字符序列的行
【发布时间】:2017-02-12 05:04:47
【问题描述】:

有时我们需要从流中读取行,但只考虑特定的字符序列作为换行符(CRLF,而不是 CR 或 LF)。

StreamReader.ReadLine,如文档所述,将其视为换行符序列 CRLF、CR 和 LF。如果该行可以包含单个 CR ("\r") 或单个 LF ("\n") 作为业务价值数据,这可能是不可接受的。

需要具备逐行读取流的能力,但由特定的字符序列分隔。

【问题讨论】:

    标签: c# stream delimiter streamreader readline


    【解决方案1】:

    这是一个从流中读取行并将其作为字符串返回的方法:

        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));
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 2010-10-14
      • 1970-01-01
      相关资源
      最近更新 更多