HI,

I am parsing a log file that contains several thousand lines of logs.

Each entry in the log ends with the Line Feed character \n.

However some of the lines have an embedded 'CR'character in. My parser should ignore those and not treat text following the CR character as a new line e.g

This represents one single line of text LF

This should CR also be one line of text LF

However using StreamReader.Readline the second line above is returned

as:

This should

also be one line of text

Does C# have a method that will return This should be one line of text - i.e. ignore the CR which is part of the logging information and not an indication that the end of the line has been reached?

I think C# does not have that functionality but you can replace the \r \n to empty string.

You should be able to do "ReadToEnd". This will read in your entire file contents.

Once you have this string, you can "Split" it using a specified character. (In your case '\n')

Double posted somehow. -Delete Me Please-

With the existing design I am current looking at a line where:-

logLine = reader.ReadLine();

To implement your solution would require changes outside the method call.
I want a simple fix that replaces or modifies the "reader.Readline" statement so that when it reads a line it ignores CR or \r in the line and returns lines terminated by \n only.

Thanks !

This will do what you want. It's an extension method to the class StreamReader:

using System;
using System.IO;
using System.Text;

namespace ExtensionMethods {
    static class Extensions {
        public static String ReadLine(this StreamReader sr, char c) {
            StringBuilder sb = new StringBuilder();
            int character;

            if (sr.EndOfStream == false) {
                do {
                    character = sr.Read();
                    sb.Append((char)character);
                } while (character != c && sr.EndOfStream == false);
                return sb.ToString();
            }

            return null;
        }
    }
}

And you use it like this

using System;
using System.IO;
using ExtensionMethods;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            StreamReader sr = new StreamReader("test.txt");

            String line;

            while ((line = sr.ReadLine('e')) != null) {
                Console.WriteLine(line);
            }

            Console.ReadLine();
        }
    }
}

The parameter to ReadLine is the character you want to break lines on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.