开发者

How to read a textfile using C#.Net

I have a text 开发者_如何学JAVAfile. 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#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜