开发者

Can I make the StreamReader "believe" that EOL is now "###" and not "\n"?

开发者 https://www.devze.com 2023-01-09 00:24 出处:网络
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).

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 ReadLineyourself, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号