本文介绍了为什么在CH375复位一个StreamReader不允许重新读取UTF8字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在重置一个StreamReader导致奇怪的行为。第一个断言成功,而第二次失败。要纠正它一(坏的)解决方案包括在CH375复位到位置3,而不是0:sr.BaseStream.Position = 3;



使用(VAR SR =新的StreamReader(@C:\temp\test.txt,Encoding.UTF8))// test.txt的在UTF8
编码{
VAR读= sr.ReadLine();
Assert.AreEqual(FROMFILE,读); // OK
sr.BaseStream.Position = 0;
sr.DiscardBufferedData();
读= sr.ReadLine();
Assert.AreEqual(FROMFILE,读); //失败
}


解决方案

您刚才没T设法的真正的重置对象。有名为类 _checkPreamble 私有字段。它将被设置为的,因为它已经被选中。你可以破解它:

 使用的System.Reflection; 
...
VAR网络= typeof运算(的StreamReader).GetField(_ checkPreamble,BindingFlags.NonPublic可| BindingFlags.Instance);
fi.SetValue(SR,真);
读= sr.ReadLine();
Assert.AreEqual(FROMFILE,读); //现在没事了



当然,你真的不想写这样的代码中。该解决方案是很琐碎,只需要创建一个新的StreamReader对象。


Reseting a StreamReader leads to strange behaviour. The first assert succeeds whereas the second fails. To correct it one (bad) solution consists in reseting to position 3 instead of 0: sr.BaseStream.Position = 3;

using (var sr = new StreamReader(@"c:\temp\test.txt", Encoding.UTF8)) // test.txt is encoded in UTF8
{
     var read = sr.ReadLine();
     Assert.AreEqual("fromfile", read); // ok
     sr.BaseStream.Position = 0;
     sr.DiscardBufferedData();
     read = sr.ReadLine();
     Assert.AreEqual("fromfile", read); //fails
}
解决方案

You just didn't manage to truly reset the object. There's a private field in the class named _checkPreamble. It will be set to false since it was already checked. You can hack it:

using System.Reflection;
...
     var fi = typeof(StreamReader).GetField("_checkPreamble", BindingFlags.NonPublic | BindingFlags.Instance);
     fi.SetValue(sr, true);
     read = sr.ReadLine();
     Assert.AreEqual("fromfile", read); // okay now

Of course you don't really want to write code like this. The solution is very trivial, just create a new StreamReader object.

这篇关于为什么在CH375复位一个StreamReader不允许重新读取UTF8字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:02