简体   繁体   中英

Stream read line

I have a stream reader line by line ( sr.ReadLine() ). My code counts the line-end with both line endings \\r\\n and/or \\n .

        StreamReader sr = new System.IO.StreamReader(sPath, enc);

        while (!sr.EndOfStream)
        {
            // reading 1 line of datafile
            string sLine = sr.ReadLine();
            ...

How to tell to code (instead of universal sr.ReadLine() ) that I want to count new line only a full \\r\\n and not the \\n ?

It is not possible to do this using StreamReader.ReadLine. As per msdn :

A line is defined as a sequence of characters followed by a line feed ("\\n"), a carriage return ("\\r"), or a carriage return immediately followed by a line feed ("\\r\\n"). The string that is returned does not contain the terminating carriage return or line feed. The returned value is null if the end of the input stream is reached.

So yoг have to read this stream byte-by-byte and return line only if you've captured \\r\\n

EDIT

Here is some code sample

private static IEnumerable<string> ReadLines(StreamReader stream)
{
    StringBuilder sb = new StringBuilder();

    int symbol = stream.Peek();
    while (symbol != -1)
    {
        symbol = stream.Read();
        if (symbol == 13 && stream.Peek() == 10)
        {
            stream.Read();

            string line = sb.ToString();
            sb.Clear();

            yield return line;
        }
        else
            sb.Append((char)symbol);
    }

    yield return sb.ToString();
}

You can use it like

foreach (string line in ReadLines(stream))
{
   //do something
}

你不能用ReadLine来做,但你可以这样做:

stream.ReadToEnd().Split(new[] {"\r\n"}, StringSplitOptions.None)

For simplification, let's work over a byte array:

    static int NumberOfNewLines(byte[] data)
    {
        int count = 0;
        for (int i = 0; i < data.Length - 1; i++)
        {
            if (data[i] == '\r' && data[i + 1] == '\n')
                count++;
        }
        return count;
    }

If you care about efficiency, optimize away, but this should work.

You can get the bytes of a file by using System.IO.File.ReadBytes(string filename) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM