Stream Seek功能未按预期反应

时间:2017-05-09 14:30:21

标签: c# filestream

目标是能够关闭流并返回到相同的位置(作为"书签")。

修改:两位用户建议我必须使用streamReader.DiscardBufferedData(),并且至少使Test1Test2的反应方式相同。我删除了Test2(有关信息:它与Test1的代码完全相同,但关闭并重新打开了流),并修复了"" Test1

Test1仍然失败:

public static void Test1(string filePath)
{
    var line1 = default(string);
    var line2 = default(string);
    var line3 = default(string);

    using (StreamReader streamReader = File.OpenText(filePath))
    {
        // read 2 consecutive lines:
        line1 = streamReader.ReadLine();
        var line2StreamPosition = streamReader.BaseStream.Position; // save position at the begining of line2:
        line2 = streamReader.ReadLine();

        // go back to the position of line2 and try to re-read it:
        streamReader.DiscardBufferedData();
        streamReader.BaseStream.Seek(line2StreamPosition, SeekOrigin.Begin);
        line3 = streamReader.ReadLine();

        if (line2 == line3)
        {
            // it doesn't reach this point
        }
        else
        {
            // it fails ...
            // it starts reading `line3` at an incorrect position
        }

    }
}

另外:var canSeek = streamReader.BaseStream.CanSeek; // true

1 个答案:

答案 0 :(得分:1)

您可以使用相应的编码来计算书签位置,但问题在于没有简单的方法来确定构成换行符的字符是什么;它不一定必须是Environment.NewLine

如果您 事先知道,在您的环境中哪些字符组成了换行符,您可以执行以下操作:

var line2StreamPosition = streamReader.CurrentEncoding
                                      .GetByteCount(
                                           string.Concat(line1, myNewLine)
                                                 .ToArray());