本文介绍了StreamReader和寻求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用streamreader读取正常的文本文件,然后在读取过程中保存当前位置后关闭streamreader,然后再次打开streamreader并开始从该位置读取吗?

can you use streamreader to read a normal textfile and then in the middle of reading close the streamreader after saving the current position and then open streamreader again and start reading from that poision ?

如果不是这样,我还能在不锁定文件的情况下完成相同的情况吗?

if not what else can i use to accomplish the same case without locking the file ?

类似这样的东西:

 var fs = File.Open(@"C:\testfile.txt", FileMode.Open, FileAccess.Read);
        var sr = new StreamReader(fs);
        Debug.WriteLine(sr.ReadLine());//Prints:firstline
        var pos = fs.Position;
        while (!sr.EndOfStream)
        {
            Debug.WriteLine(sr.ReadLine());
        }
        fs.Seek(pos, SeekOrigin.Begin);
        Debug.WriteLine(sr.ReadLine());//Prints Nothing, i expect it to print SecondLine.






@lasseespeholt


@lasseespeholt

这是我尝试过的代码

            var position = -1;
        StreamReaderSE sr = new StreamReaderSE(@"c:\testfile.txt");
        Debug.WriteLine(sr.ReadLine());
        position = sr.BytesRead;
        Debug.WriteLine(sr.ReadLine());
        Debug.WriteLine(sr.ReadLine());
        Debug.WriteLine(sr.ReadLine());
        Debug.WriteLine(sr.ReadLine());
        Debug.WriteLine("Wait");
        sr.BaseStream.Seek(position, SeekOrigin.Begin);
        Debug.WriteLine(sr.ReadLine());


推荐答案

是的,可以看到:

var sr = new StreamReader("test.txt");
sr.BaseStream.Seek(2, SeekOrigin.Begin); // Check sr.BaseStream.CanSeek first

更新:
请注意,不必将 sr.BaseStream.Position 用于任何有用的东西,因为 StreamReader 使用缓冲区,因此它不会反映您实际阅读的内容。我想您会找不到真正的位置。因为您不能只计算字符(不同的编码以及因此的字符长度)。我认为最好的方法是使用 FileStream 本身。

Update:Be aware that you can't necessarily use sr.BaseStream.Position to anything useful because StreamReader uses buffers so it will not reflect what you actually have read. I guess you gonna have problems finding the true position. Because you can't just count characters (different encodings and therefore character lengths). I think the best way is to work with FileStream´s themselves.

更新:
从此处使用 TGREER.myStreamReader

此类添加了 BytesRead 等。(与 ReadLine()一起使用,显然不使用其他读取方法)
,然后您可以这样:

Update:Use the TGREER.myStreamReader from here:http://www.daniweb.com/software-development/csharp/threads/35078this class adds BytesRead etc. (works with ReadLine() but apparently not with other reads methods)and then you can do like this:

File.WriteAllText("test.txt", "1234\n56789");

long position = -1;

using (var sr = new myStreamReader("test.txt"))
{
    Console.WriteLine(sr.ReadLine());

    position = sr.BytesRead;
}

Console.WriteLine("Wait");

using (var sr = new myStreamReader("test.txt"))
{
    sr.BaseStream.Seek(position, SeekOrigin.Begin);
    Console.WriteLine(sr.ReadToEnd());
}

这篇关于StreamReader和寻求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 07:06