[英]Extract specific lines of text from a text file c#
我正在使用StreamReader逐行讀取文本文件,並將其顯示到控制台。 它讀入並顯示正常。 每行從左到右包含日期,時間,數字,條目。 文本文件包含數百行文本。 我想允許用戶輸入特定的日期和時間,並且只獲取該時間范圍內的文本行。 因此,在數百行文本中,只能針對輸入的日期和時間返回文本行。
到目前為止,這是我的代碼,可以閱讀並顯示文本文件。
public override void ReadFile(string strFileName)
{
try
{
using (StreamReader sr = new StreamReader(@"C:\MyFolder\TextFile.txt"))
{
String line = sr.ReadLine();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
這可以正常工作並在控制台上顯示文本,如下所示:
01-01-2015 10:10:10 Line of text blah blah blah
01-01-2015 10:10:10 Line of text blah blah blah
01-01-2015 10:10:10 Line of text blah blah blah
現在,我試圖將行分開以獲取各個部分,例如日期和時間。 到目前為止,這是我所擁有的,但是我不確定什么是最好的進行方式。
public override void ReadLiFile(string strFileName)
{
try
{
using (StreamReader sr = new StreamReader(@"C:\MyFolder\TextFile.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] fields = line.Split("\t".ToCharArray());
int theInt = Convert.ToInt32(fields[0]);//to get first field e.g Date
}
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
我想根據給定的日期和時間縮小輸出到屏幕的范圍。 我不希望所有行僅顯示與特定日期和時間相關的行,例如在01-01-2015 10:10:10和01-01-2015 10:15:15之間的行
我猜我需要隔離每一行中的日期和時間字段並存儲值。 我試圖拆分線並存儲第一個值是Date。 我的問題是拆分行中字段的最佳方法是什么? 我的嘗試不起作用。 我現在正得到一條錯誤消息,提示“無法讀取文件”以及“輸入字符串的格式不正確”。謝謝您的幫助。
這將提取日期部分並將其解析為DateTime
,然后您可以對其進行過濾。
var startDate = new DateTime(2015, 1, 1, 10, 10, 10);
var endDate = new DateTime(2015, 1, 1, 10, 15, 15);
var result = (from line in File.ReadLines(@"C:\MyFolder\TextFile.txt")
let pieces = line.Split('\t')
let date = DateTime.ParseExact(pieces[0] + pieces[1], "MM-dd-yyyyHH:mm:ss", CultureInfo.InvariantCulture)
where date >= startDate && date <= endDate
select line).ToList();
這是LINQ,以防您以前從未看過它。 一旦習慣了,它對查詢非常有用。
let
關鍵字允許您存儲數據,這樣(例如)您可以在整個查詢中多次使用它,而無需多次執行ParseExact
或Split
。
File.ReadLines
從文件中讀取盡可能少的行,足以滿足您的查詢。 盡管在這種情況下,必須解析每一行以檢查日期,但無論如何,它始終在讀取它們。
DateTime dt;
if (DateTime.TryParse(fields[0] + " " + fields[1], out dt))
if (dt >= minDate && dt <= maxDate)
這應該在startDate
和endDate
之間打印所有帶有Date的行。 我已經省略了時間部分,但是您應該了解如何做。
DateTime startDate = new DateTime(2015, 1, 1);
DateTime endDate = new DateTime(2015, 1, 3);
var query = File.ReadLines(@"e:\1.txt").Select(line => new { Line = line, Date = Convert.ToDateTime(line.Split(' ').First()) })
.Where(x => x.Date >= startDate && x.Date <= endDate);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.