0

I have a function in c# class which is reading a textfile into streamreader.Here is the c# function.

public readFile(string fileName, long startPosition = 0)
    {
        //Open the file as FileStream
        _fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        _reader = new StreamReader(_fileStream);
        //Set the starting position
        _fileStream.Position = startPosition;

    }

and i am trying to call this function into another class and read the file line by line.

 private AddedContentReader _freader;
 protected override void OnStart(string[] args)
    {
            _freader = new AddedContentReader(file);    

    }

So my question is how to read the textfile line by line in the calling function

Please help me..

user3816352
  • 187
  • 2
  • 5
  • 17
  • have you checked [this post](http://stackoverflow.com/questions/8037070/whats-the-fastest-way-to-read-a-text-file-line-by-line)? – Yuliam Chandra Jul 25 '14 at 05:56

3 Answers3

2

The StreamReader class has a method called ReadLine.

Sample

string line;
while((line = _reader.ReadLine()) != null)
{
   Console.WriteLine (line);
}

More Information

dknaack
  • 60,192
  • 27
  • 155
  • 202
  • One small query `protected override void OnStart(string[] args) { _freader = new AddedContentReader(file); }` inside this method because i am keeping my logic here.. – user3816352 Jul 25 '14 at 06:07
  • If you want to use it in you OnStart method, why not return it from the readfile method. – dknaack Jul 25 '14 at 06:08
  • Iam not sure what you want to do exactly. Do you want to use your StreamReader in your OnStart Method? What is you AddedContentReader doing? – dknaack Jul 25 '14 at 06:12
0

Use while loop to read till the line is empty or nil. I hope below code will help you.

TextReader yourfile;
yourfile = File.OpenText("Your File Path");

while ((str = yourfile.ReadLine()) != null)
            {

//write your code here
}

yourfile.Close();
Balaji Kondalrayal
  • 1,743
  • 3
  • 19
  • 38
0

One way to do it is to get all the lines first and then loop through them using the readlines method of system.IO in code such as the following:

            string[] lines = File.ReadAllLines(fileName);
            int count = 0;                

            while(lines.Length > count)
            {
                function1(lines[count]]);
                count++;        
            }
Brian Low
  • 11,605
  • 4
  • 58
  • 63
Robert Anderson
  • 1,246
  • 8
  • 11