我正在尝试读取我创建的文件,其中包含整个程序中的所有日志行。我有以下鳕鱼:
private string ReadEmailLog(string EmailLog)
{
TextReader tr = new StreamReader(EmailLog);
tr.ReadLine();
tr.Close();
}
我需要读取EmailLog文件的每一行,然后将其返回到名为message的字符串中。我如何让这个方法返回整个日志文件,每一行?
答案 0 :(得分:5)
您可以使用File.ReadAllText
或File.ReadAllLines
。
如果您使用的是.NET 4.0,还可以使用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);
}
这允许您将文件I / O作为LINQ操作的一部分。
答案 1 :(得分:1)
尝试
tr.ReadToEnd();
将返回包含文件所有内容的字符串 TextReader.ReadToEnd Method
如果您希望获得string[]
中的行,那么
tr.ReadToEnd().Split("\n");
应该这样做,同时将线条分隔为“\ n”字符,表示回车符和换行符组合字符(换行符)。
答案 2 :(得分:1)
只需使用:
String text = tr.ReadToEnd();
答案 3 :(得分:0)
您可以阅读所有内容或日志并将其返回。例如:
private string void ReadEmailLog(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
return logreader.ReadToEnd();
}
}
或者,如果您希望每行一个:
private IEnumerable<string> ReadEmailLogLines(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
string line = logreader.ReadLine();
while(line != null)
{
yield return line;
}
}
}
答案 4 :(得分:-1)
tr.ReadToEnd(); //read whole file at once
// or line by line
While ( ! tr.EOF)
tr.ReadLine()//