Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between StreamReader(string filepath) and StreamReader(Stream _stream)

I am little confused between two different constructor of StreamReader class i.e

1.StreamReader(Stream)

I know it takes stream bytes as input but the respective output is same.

here is my code using StreamReader(Stream) contructor

string filepath=@"C:\Users\Suchit\Desktop\p022_names.txt";
using(FileStream fs = new FileStream(filepath,FileMode.Open,FileAccess.Read))
{
     using(StreamReader sw = new StreamReader(fs))
     {
         while(!sw.EndOfStream)
         {
             Console.WriteLine(sw.ReadLine());
         }
     }
}

2. StreamReader(String)

This conrtuctor takes the physical file path,
where our respective file   exists but the output is again same.

Here is my code using StreamReader(String)

string filepath=@"C:\Users\Suchit\Desktop\p022_names.txt";
using (StreamReader sw = new StreamReader(filePath))
{
     while(!sw.EndOfStream)
     {
         Console.WriteLine(sw.ReadLine());
     }
}

So, Which one is better? When and where we should use respective code, so that our code become more optimized and readable?

like image 253
Himanshu Jain Avatar asked Mar 18 '26 03:03

Himanshu Jain


2 Answers

A class StreamReader (as well as StreamWriter) is just a wrapper for FileStream, It needs a FileStream to read/write something to file.

So basically you have two options (ctor overloads) :

  1. Create FileStream explicitly by yourself and wrap SR around it
  2. Let the SR create FileStream for you

Consider this scenario :

        using (FileStream fs = File.Open(@"C:\Temp\1.pb", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (StreamReader reader = new StreamReader(fs))
            {
                // ... read something                       

                reader.ReadLine();

                using (StreamWriter writer = new StreamWriter(fs))
                {
                    // ... write something

                    writer.WriteLine("hello");
                }
            }
        }

Both reader and writer works with the same filestream. Now if we change it to :

        using (StreamReader reader = new StreamReader(@"C:\Temp\1.pb"))
        {
            // ... read something                       

            reader.ReadLine();

            using (StreamWriter writer = new StreamWriter(@"C:\Temp\1.pb"))
            {
                // ... write something

                writer.WriteLine("hello");
            }
        }

System.IOException is thrown "The process cannot access the file C:\Temp\1.pb because it is being used by another process... This is because we try to open file with FileStream2 while we still use it in FileStream1. So generally speaking if you want to open file, perform one r/w operation and close it you're ok with StreamReader(string) overload. In case you would like to use the same FileStream for multiple operations or if by any other reason you'd like to have more control over Filestream then you should instantiate it first and pass to StreamReader(fs) .

like image 67
Fabjan Avatar answered Mar 19 '26 17:03

Fabjan


Which one is better?

None. Both are same. As the name suggests StreamReader is used to work with streams; When you create an instance of StreamReader with "path", it will create the FileStream internally.

When and where we should use respective code

When you have the Stream upfront, use the overload which takes a Stream otherwise "path".

One advantage of using Stream overload is you can configure the FileStream as you want. For example if you're going to work with asynchronous methods, you need to open the file with asynchronous mode. If you don't then operation will not be truly asynchronous.

When at doubt don't hesitate to check the source yourself.

like image 39
Sriram Sakthivel Avatar answered Mar 19 '26 16:03

Sriram Sakthivel