is FileStream necessary?

J

John Salerno

In Murach's C#, it shows that StreamWriter and StreamReader both take a
stream object as a parameter, and the book's examples of these two
classes all first create a FileStream object. But I notice in the VS
help files that they use the two classes directly, without creating a
stream, and that StreamWriter and StreamReader can both take a string
parameter as well. Is this new to .NET 2.0? What's the difference
between doing this and explicitly creating a FileStream object? Is it
called implicitly anyway?
 
T

Truong Hong Thi

They are just about the same. If you pass a file path instead of a
stream, .NET will internally create a FileStream for that file.
 
J

Jon Skeet [C# MVP]

John said:
In Murach's C#, it shows that StreamWriter and StreamReader both take a
stream object as a parameter, and the book's examples of these two
classes all first create a FileStream object. But I notice in the VS
help files that they use the two classes directly, without creating a
stream, and that StreamWriter and StreamReader can both take a string
parameter as well. Is this new to .NET 2.0? What's the difference
between doing this and explicitly creating a FileStream object? Is it
called implicitly anyway?

Yes, a FileStream is created anyway. The difference is that by creating
the FileStream yourself, you can specify different file modes, share
access etc.

Jon
 
W

William Stacey [MVP]

It is a bit confusing at first I agree. Also, things like the static
File.Open() method also return a StreamReader with also wraps a FileStream.
IIRC, all file operations eventually have a FileStream as the base stream.
 
J

John Salerno

John said:
In Murach's C#, it shows that StreamWriter and StreamReader both take a
stream object as a parameter, and the book's examples of these two
classes all first create a FileStream object. But I notice in the VS
help files that they use the two classes directly, without creating a
stream, and that StreamWriter and StreamReader can both take a string
parameter as well. Is this new to .NET 2.0? What's the difference
between doing this and explicitly creating a FileStream object? Is it
called implicitly anyway?

Thanks guys!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top