C# 如何在C语言中从文本文件中获取特定行#
我有一个包含如下数据的文本文件 输入数据文件类型:INdia.TxtC# 如何在C语言中从文本文件中获取特定行#,c#,c#-3.0,C#,C# 3.0,我有一个包含如下数据的文本文件 输入数据文件类型:INdia.Txt INdia(s) - Input Data File Exists ..... **------------------------------------------** Feed Counts: **------------------------------------------** Records in the Input File : 04686 Records Inserted in T
INdia(s) - Input Data File Exists .....
**------------------------------------------**
Feed Counts:
**------------------------------------------**
Records in the Input File : 04686
Records Inserted in Table : 04069
Records Inserted in Table : 00617
**-------------------------------------------**
我只需要在输出文件中获取这些数据
Records in the Input File : 04686
Records Inserted in Table : 04069
Records Inserted in Table : 00617
我正在使用的代码
try
{
int NumberOfLines = 15;
string[] ListLines = new string[NumberOfLines];
using (FileStream fs = new FileStream(@"d:\Tesco\NGC\UtilityLogs\Store.log", FileMode.Open))
{
using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
if (line.Contains("Records"))
{
//Read the number of lines and put them in the array
for (int i = 8; i < NumberOfLines; i++)
{
ListLines[i] = reader.ReadLine();
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
试试看
{
int NumberOfLines=15;
string[]ListLines=新字符串[NumberOfLines];
使用(FileStream fs=newfilestream(@“d:\Tesco\NGC\UtilityLogs\Store.log”,FileMode.Open))
{
使用(StreamReader=newstreamreader(fs,Encoding.UTF8))
{
字符串行=null;
而((line=reader.ReadLine())!=null)
{
控制台写入线(行);
如果(第行包含(“记录”))
{
//读取行数并将其放入数组中
对于(int i=8;i
试试这个
while ((line = reader.ReadLine()) != null)
{
if(!line.Contains("Records")) //if line does not contain "Records"
{
continue; //skip to next line/iteration
}
//else
//process the line
}
如果已知行数,那么这可能会起作用
int line_number = 1;
int startline = 15;
int endline = 100;
while ((line = reader.ReadLine()) != null)
{
if(line_number >= startline && line_number <= endline)
{
//process the line
}
line_number++;
}
int line_number=1;
int=15;
int endline=100;
而((line=reader.ReadLine())!=null)
{
如果(行号>=行号和行号如果文件内容固定,则使用索引
使用StreamReader读取文件,然后按换行符拆分StreamReader数据,您将获得一个数组,然后为该数组设置索引。如果文件中的行数始终相同,请使用:
string[] lines = File.ReadAllLines(fileName);
string line1 = lines[5];
string line2 = lines[6];
string line3 = lines[6];
...
甚至像这样:
string[] lines = File.ReadAllLines(fileName);
string[] result = new string[3]; // No matter how many, but fixed
Array.Copy(lines, 5, result, result.Length);
如果标题始终为5行,并且文件始终以一行结束,则您甚至可以拥有动态行数:
string[] lines = File.ReadAllLines(fileName);
string[] result = new string[lines.Length - 6];
Array.Copy(lines, 5, result, result.Length);
此LINQ查询将为您提供IEnumerable
,其中将包含文件中以“Records”字符串开头的所有行:
哈!这太棒了!+1来自我。
var lines = File.ReadAllLines(path).Where(line => line.StartsWith("Records"));