开发者

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 metho开发者_开发问答d to return the whole log file, every line?


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.


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).


simply use:

    String text = tr.ReadToEnd();


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;
        }
    }
}


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

// or line by line

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜