简体   繁体   中英

How to read a textfile using C#.Net

I have a text file. I want read that file. But In that if the line starts with 6 then i want read that file otherwise leave that line and go to next line. If the line starts with 6 then i want to read that line from position 6 to 15 and 45 to 62. I want to implement this code in C#.NET. How to write that code? Can anyone Help me.

public IEnumerable<string> ReadLines(string fileName)
{
    string line;
    using (var rdr = new StreamReader(fileName))
        while ( (line = rdr.ReadLine()) != null)
            yield return line;
}

ReadLines("yourfile.txt")
    .Where(l => l.StartsWith("6"))
    .Select(l => new {Part1 = l.SubString(6, 9), Part2 = l.SubString(45, 17)});

using System.IO

Use Microsoft's StreamReader . Example here. but use the Read(..) method for characters, Peek(..) to look ahead, etc.

StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.

You need to use System.IO.TextReader classes & string functions to read the file & check the contents of each line.

MSDN has a nice example in this article using StreamReader in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM