如何在c#中从文本文件中读取多行

时间:2014-10-27 10:43:05

标签: c# .net text-files streamreader

我有一个包含用户记录的文本文件。在文本文件中,一行用户记录存在于三行文本文件中。现在根据我的要求,我必须为一个用户读取前三行,处理并插入数据库和第二个用户的下三行等等。

以下是我用于从文本文件中单行读取的代码..

        if (System.IO.File.Exists(location) == true)
        {
            using (StreamReader reader = new StreamReader(location))
            {
                while ((line = reader.ReadLine()) != null)
                {     
                        line = line.Trim();
                }
        }   
        }

请帮我阅读多行,在这种情况下,从文本文件中删除3行。

谢谢..

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

if (System.IO.File.Exists(location) == true)
        {
            var lines=File.ReadAllLines(location);
            int usersNumber = lines.Count() / 3;
            for(int i=0; i < usersNumber; i++){
                var firstField=lines[i*3];
                var secondField=lines[i*3 +1];
                var thirdField=lines[i*3 +2];
                DoStuffs(firstField,secondField,thirdField);
            }
            if(lines.Count() > usersNumber *3) //In case there'd be spare lines left
                 DoSomethingElseFrom(lines, index=(usersNumber*3 +1));
        }

您正在阅读文件的所有行,计算您拥有的用户数(3个组),然后为每个组检索其关联信息,最后您正在处理3个组与同一用户相关的字段。

答案 1 :(得分:1)

我使用了包含此内容的虚拟源文件:

line1_1 /*First line*/
line1_2
line1_3
line2_1 /*second line*/
line2_2
line2_3
line3_1 /*third line*/
line3_2
line3_3
line4_1 /*fourth line*/
line4_2
line4_3

string result = String.Empty;
string location = @"c:\users\asdsad\desktop\lines.txt";
if (System.IO.File.Exists(location) == true)
    {
        using (StreamReader reader = new StreamReader(location))
        {
            string line = String.Empty;
            while ((line = reader.ReadLine()) != null) /*line has the first line in it*/
            {
                for(int i = 0; i<2; i++) /*only iterate to 2 because we need only the next 2 lines*/
                    line += reader.ReadLine(); /*use StringBuilder if you like*/
                result += line; 
            }
    }   
    result.Dump(); /*LinqPad Only*/

答案 2 :(得分:0)

void Main()
{
    var location = @"D:\text.txt";
    if (System.IO.File.Exists(location) == true)
    {
        using (StreamReader reader = new StreamReader(location))
        {
            const int linesToRead = 3;
            while(!reader.EndOfStream)
            {
                string[] currReadLines = new string[linesToRead];
                for (var i = 0; i < linesToRead; i++)
                {
                    var currLine = reader.ReadLine();
                    if (currLine == null)
                        break;

                    currReadLines[i] = currLine;
                }

                //Do your work with the three lines here
                //Note; Partial records will be persisted
                //var userName = currReadLines[0] ... etc...
            }
        }
    }
}