Difference between StreamReader (file string path) and StreamReader (Stream _stream)

I am a bit confused between two different constructors of the StreamReader ie class

1.StreamReader (stream)

I know the input is used to input the stream bytes, but the corresponding output is the 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 should we use the appropriate code to make our code more streamlined and readable?

+3


source to share


7 replies


class StreamReader

(and also StreamWriter

) is just a wrapper class for FileStream

, so it needs to work with fs to read / write something to a file.

So you have two options (overload ctor):

  • Create FileStream explicitly yourself and wrap SR around it
  • Let SR create the 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 work with the same file stream. 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 are trying to open the file with FileStream2 while we are still using it in FileStream 1. Typically, if you want to open a file, do one r / w operation and close it, you can with overload StreamReader(string)

. If you want to use the same one FileStream

for multiple operations, or if there is any other reason why you would like to have more control over the Filestream, then you must first instantiate it and navigate to StreamReader(fs)

.

+3


source


Which one is better?

Is absent. Both are the same. As the name suggests, it is StreamReader

used for working with streams; When you instantiate StreamReader with "path", it will instantiate FileStream

internally.

When and where should we use the appropriate code



If you have a preview Stream

, use an overload that takes a Stream

different path . "

One of the benefits of using overload Stream

is that you can customize FileStream

as you see fit. For example, if you are going to work with asynchronous methods, you need to open a file with asynchronous mode. If you don't, the operation won't be truly asynchronous .

If in doubt, feel free to check the source yourself .

+1


source


Please note that overloading Stream

does not accept FileStream

. This allows you to read data from any subclass Stream

, which allows you to do things like read the result of a web request, read unpacked data, or read decrypted data.

Use an overload string path

if you only want to read from a file and you don't need to use it FileStream

for anything else. It just saves you the trouble of writing a line of code:

using (var stream = File.OpenRead(path))
using (var reader = new StreamReader(stream))
{
    ...
}

      

File.OpenText

also does the same.

+1


source


Both are the same, just overload, use one according to your needs. If you have a local file you can use StreamReader(string path)

otherwise, if you only have a stream from online or other source then another overload will help you ieStreamReader(Stream stream)

0


source


Well after looking for a new open source reference . You can see that the last inner expands to the previous one. So passing the raw file path to StreamReader

makes it internally expand to FileStream

. To me this means both are equivalent and you can use them however you want.

My personal opinion is to use the latter because its less code to write and its more explicit. I don't like the way java does it with thousands of bytes, thread safe, output handlers, etc ...

0


source


Basically both work the same, which is what UTF8Encodeing does and uses a 1024 Byte Buffer . But the StreamReader calls Dispose () on the provided Stream when StreamReader.Dispose is called.

You can refer to the following Stream and String

You can use either of them depending on whether you have manually a Stream or String. Hope this is clear.

0


source


StreamReader (string) is just an overload of StreamReader (Stream).

In the context of your question, you're probably better off using the StreamReader (string) overload, simply because it means less code. StreamReader (Stream) can be very fast, but you have to create a FileStream using a string, which you could simply insert directly into the StreamReader so that any benefit is lost.

Basically, StreamReader (String) is for files with static or easily mapped paths (as you think), while StreamReader (Stream) can be thought of as a fallback in case you have access to the file programmatically, but its path is difficult define.

0


source







All Articles