我是 C# 新手,我已经开始使用
StreamReader
。我试图一次读取一行文件,并在它与“I/RPTGEN”等特定关键字匹配时输出该行。
到目前为止,我弄清楚了如何将整个文件读入字符串,但我无法弄清楚如何一次只读取一行。
到目前为止我的代码是这样的。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Test
{
public static void Main()
{
try
{
using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv"))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
Console.ReadLine();
}
}
catch (Exception e)
{
Console.WriteLine("The File could not be read:");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
此外,这里是文件中一行的示例。
咨询,2013 年 2 月 27 日上午 12:00:44,I/RPTGEN(cadinterface),I/RPTGEN 失败 - 错误 500 - 内部服务器错误 - 针对报告请求返回(检查 URL 日志)。
如果您的 CSV 文件仅包含一行,则
ReadToEnd
是可以接受的,但如果您的日志文件由多行组成,那么最好使用 ReadLine
对象的 StreamReader
逐行读取
using (StreamReader sr = new StreamReader("c:/temp/ESMDLOG.csv"))
{
string currentLine;
// currentLine will be null when the StreamReader reaches the end of file
while((currentLine = sr.ReadLine()) != null)
{
// Search, case insensitive, if the currentLine contains the searched keyword
if(currentLine.IndexOf("I/RPTGEN", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
Console.WriteLine(currentLine);
}
}
}
另一种一次读取一行的方法是:
var searchItem = "Error 500";
var lines = File.ReadLines("c:/temp/ESMDLOG.csv");
foreach (string line in lines)
{
if (line.Contains(searchItem))
{
Console.WriteLine(line);
}
}