I have a file and I need to read it line after line. Each line ends with "###" and not with the regular end-of-line character (\n).
Is there any way to change the streamReader so when I use the ReadLine() it will read until it sees "###"? If not, is there another 开发者_如何学Cway to do it or should I implement a new class for this purpose?
No, you cannot do this with StreamReader
. The StreamReader class is hardcoded to recognize \r
and \n
characters and it is not configurable. You can see this using .NET Reflector:
char ch = this.charBuffer[charPos];
switch (ch)
{
case '\r':
case '\n':
string str;
if (builder != null)
// ...
If your files are not too large you can instead read the entire file into memory and then split on ###
. If you need the streaming behaviour then you could write something similar to ReadLine
yourself, but with the behaviour you desire.
[joke] using Moles framework, you can change value of Environment.NewLine
MEnvironemnt.NewLineGet = () => "###";
and hope that streamreader uses this [/joke]
but i guess its easier to just inherit from streamreader and override one method...
The end of line behaviour is hard-coded in StreamReader.ReadLine.
If you want to override this or at least see how it works so you can make your own TextReader, don't forget you can get the framework source from MS ( http://referencesource.microsoft.com/netframework.aspx )
There are two ways I can think of to do this. The first is to write an extension method on StreamReader that does what you want and use that instead. The second is to define a new Encoding object that will translate ### into \n (and possibly translate \n into something else).
One option (depending on performance concerns) is to do a simple read()
and look for "###" in the input stream to do whatever you want with it.
精彩评论