user3816352
user3816352

Reputation: 187

Reading line by line from textfile

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

Upvotes: 0

Views: 150

Answers (3)

Robert Anderson
Robert Anderson

Reputation: 1256

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++;        
            }

Upvotes: 0

Balaji Kondalrayal
Balaji Kondalrayal

Reputation: 1751

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();

Upvotes: 0

dknaack
dknaack

Reputation: 60556

The StreamReader class has a method called ReadLine.

Sample

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

More Information

Upvotes: 2

Related Questions