如何通过一些行来读取文本文件行? [英] How to read the text file lines with passing over some lines?
问题描述
我有一个文本文件,其中包含一些行信息.我想通过一些内容来阅读它.例如,假设我的行数为1-10.当我正在阅读时,我想通过以下方式阅读它
1<-我想阅读此内容
2<-跳过此
3<-阅读此
4<-跳过此
5<-阅读此内容
6<-跳过此
7<-阅读此内容
8<-跳过此
9<-阅读此内容
10<-跳过此
你的模式正确吗?我如何使用C#实现呢?我也想稍后再跳过这些行.有任何想法吗?
I have a text file that contains some info in lines. I wanna read it by passing over some lines. For example, let''s say i have 1-10 in the lines. When i''m reading i want to read it in the following way
1 <- i wanna read this
2 <- Skip this
3 <- read this
4 <- Skip this
5 <- read this
6 <- Skip this
7 <- read this
8 <- Skip this
9 <- read this
10 <- Skip this
you get the pattern right? how can i achieve this using c#? and i wanna get the lines i skipped at a later time too. Any ideas?
推荐答案
因为您无法真正知道每行有多长时间,所以没有一种简单的方法可以在不先阅读的情况下跳过一行. /> 通常,您必须读取所有行,但丢弃2条偶数行.
Because you can''t really know how long is each line, there is no easy way to skip a line without reading it first.
Typically you''ll have to read all the lines but discard the 2 even lines.
string filePath = @"c:\windows\win.ini";
using (var fileReader = new System.IO.StreamReader(filePath))
{
int lineNo = 1;
string line;
while (true)
{
line = fileReader.ReadLine();
if (line == null) break; // we have reached the end of the file
bool oddLine = ((lineNo % 2) == 1);
if (oddLine) Console.WriteLine(lineNo + " " + line);
lineNo++;
}
}
这将输出每隔一行:
This will output every other line:
1 ; for 16-bit app support
3 [extensions]
5 [files]
7 MAPI=1
9 CMC=1
11 MAPIXVER=1.0.0.1
13 [MCI Extensions.BAK]
15 3gp=MPEGVideo
17 3gpp=MPEGVideo
19 adt=MPEGVideo
21 m2t=MPEGVideo
23 m2v=MPEGVideo
您遇到了上述问题.但是,我可以为您提供一种更简单的阅读方法:
You have the problem as stated above. However, I can give you an even easier way to readlines:
string[] lines = File.ReadLines(filePath);
请参阅 http://msdn.microsoft.com/en-us/library/dd383503.aspx [ ^ ]
See http://msdn.microsoft.com/en-us/library/dd383503.aspx[^]
看这个例子:-
look this example:-
private void ReadLinesNoFromFile(string FileNameWithPath)
{
string[] bt = null;
if (System.IO.File.Exists(FileNameWithPath))
{
bt = System.IO.File.ReadAllLines(FileNameWithPath);
}
string str =""
for (int i = 0; i < bt.Length; i++)
{
if ((i+1 % 2)==1)
str = str +i.ToString() + "<- read this" + bt[i].ToString();// read file line
else
str = str + i.ToString() + "<- Skip this" // no read file line
}
}
这篇关于如何通过一些行来读取文本文件行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!