如何从c#中的文本文件中读取多行 [英] How to read multilines from text file in c#

查看:103
本文介绍了如何从c#中的文本文件中读取多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file which contains user records.In the text file one user record is present in three lines of text file.Now as per my requirement i have to read first three lines for one User, Process it and insert into database and next three lines for second user and so on..

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

Here is the code that i have used for single line reading from text files..

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

请帮我阅读多行,在本例中为文本文件中的 3 行 ..

Please help me to read multi-lines , in this case 3 lines from text file ..

谢谢..

推荐答案

我使用了一个包含以下内容的虚拟 dource 文件:

I have used a dummy dource file with this content:

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*/

这篇关于如何从c#中的文本文件中读取多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆