tags:

views:

98

answers:

3

Hi,

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.

A: 

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#.

SoftwareGeek
+2  A: 

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.

John K
+3  A: 
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)});
Joel Coehoorn
Awesome solution.
John K
Yes, but one that may be difficult for the OP to understand.
Ed Swangren
Why not File.ReadAllLines instead of your ReadLines method?
John Buchanan
I hope teachers that assign these problems google to see if they asked stackoverflow for the answer! That being said, I like your solution.
ראובן
Semantically easy to understand because of its expressiveness however not necessarily so programmatically if unfamiliar with the concepts. Any teacher will will know this answer was lifted if the level of the course is lower. Unless it's a Continuing Education course in which you often get experienced people in other languages who pick up the taught language quickly.
John K