StreamReader and seeking

后端 未结 5 460
庸人自扰
庸人自扰 2020-11-27 06:59

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 agai

5条回答
  •  余生分开走
    2020-11-27 07:12

    Yes you can, see this:

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

    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.

    Update: Use the TGREER.myStreamReader from here: http://www.daniweb.com/software-development/csharp/threads/35078 this 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());
    }
    

提交回复
热议问题