Link to home
Start Free TrialLog in
Avatar of ssdjgru1
ssdjgru1

asked on

ReadLine from FileStream

As I found out the FileStream has no function ReadLine, but just Read. Is there any way to read from filestream line by line? (Has anybody written a function for that maybe)
Avatar of AlexFM
AlexFM

You can use StreamReader class:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line;
                // Read and display lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

Having FileStream instance you can create StreamReader from it using constructor:
public StreamReader(Stream stream);


            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {

                    while (sr.Peek() >= 0)
                    {
                        Console.WriteLine(sr.ReadLine());
                    }
                }
            }
Avatar of ssdjgru1

ASKER

the sr.ReadLine returns string, but what i need is byte[]...the conversion can be made easely with getbytes, but the problem is when you have some national specific characters which are instantly converted to unicode in string and render it unuseful for me.
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial