user380432
user380432

Reputation: 4779

C# method to read text error log file

I am trying to read a file I create that contains all the logs lines throughout my program. I have the following cod:

    private string ReadEmailLog(string EmailLog)
    {
        TextReader tr = new StreamReader(EmailLog);
        tr.ReadLine();
        tr.Close();
    }

I need to read the EmailLog file, every line of it, and then put return it into a string called message. How would I get this method to return the whole log file, every line?

Upvotes: 0

Views: 4277

Answers (5)

Ali Tarhini
Ali Tarhini

Reputation: 5358

tr.ReadToEnd(); //read whole file at once

// or line by line

While ( ! tr.EOF)
tr.ReadLine()//

Upvotes: -1

John Saunders
John Saunders

Reputation: 161781

You can use File.ReadAllText or File.ReadAllLines.

If you're using .NET 4.0, you can also use File.ReadLines:

var files = from file in Directory.EnumerateFiles(@"c:\",
                "*.txt", SearchOption.AllDirectories)
            from line in File.ReadLines(file)
            where line.Contains("Microsoft")
            select new
            {
                File = file,
                Line = line
            };

foreach (var f in files)
{
    Console.WriteLine("{0}\t{1}", f.File, f.Line);
}

This allows you to make file I/O part of a LINQ operation.

Upvotes: 6

Matt Ellen
Matt Ellen

Reputation: 11602

You can read all the contents or the log and return it. For example:

private string void ReadEmailLog(string EmailLog)
{
    using(StreamReader logreader = new StreamReader(EmailLog))
    {
        return logreader.ReadToEnd();
    }
}

Or if you want each line one at a time:

private IEnumerable<string> ReadEmailLogLines(string EmailLog)
{
    using(StreamReader logreader = new StreamReader(EmailLog))
    {
        string line = logreader.ReadLine();
        while(line != null)
        {
             yield return line;
        }
    }
}

Upvotes: 0

Zain Shaikh
Zain Shaikh

Reputation: 6043

simply use:

    String text = tr.ReadToEnd();

Upvotes: 1

Will Marcouiller
Will Marcouiller

Reputation: 24132

Try

tr.ReadToEnd();

which will return a string that contains all the content of your file.
TextReader.ReadToEnd Method

If you want to get the lines in a string[], then

tr.ReadToEnd().Split("\n");

should do it, while it will separate the lines to the "\n" character, which represents a carriage return and line feed combined characters (new line character).

Upvotes: 1

Related Questions