473,395 Members | 1,583 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

StreamReader / StreamWriter vs System.IO.File.*?

I have installed the Visual C# 2005 Code Snippets, and the snippets
for file handling use StreamReader and StreamWriter, instead of
System.IO.File.*. VB 2005 code snippets don't use these. Why are
they suggesting the use of these classes instead of the fundamental
File methods? Are they better? I thought code snippets were supposed
show things in the easy / simple way.

What do you guys think? What should a beginner learn to do when
learning to read / write files?

Zytan

Mar 2 '07 #1
15 7102
the snippets
for file handling use StreamReader and StreamWriter
And they even use the using-statement! Which is hard to grasp quickly
(especially when the docs show it using a resource created before the
using statement block, which is strange since it is supposed to
destruct that object at the end of the block, but how can it do this
when the object it is *still in scope* after the using statement
block!?)
I thought code snippets were supposed
show things in the easy / simple way.
So, these snippets are certainly not the easiest way.

Zytan

Mar 2 '07 #2
Zytan wrote:
I have installed the Visual C# 2005 Code Snippets, and the snippets
for file handling use StreamReader and StreamWriter, instead of
System.IO.File.*. VB 2005 code snippets don't use these. Why are
they suggesting the use of these classes instead of the fundamental
File methods? Are they better? I thought code snippets were supposed
show things in the easy / simple way.

What do you guys think? What should a beginner learn to do when
learning to read / write files?
I do not have code snippets, but I think you can use
the following rule of thumb:

*Stream for binary files
*Writer/*Reader for text files (ignoring BinaryReader/BinaryWriter)

*Writer/*Reader are additional functionality on top of *Stream.

Arne
Mar 2 '07 #3
Zytan wrote:
>the snippets
for file handling use StreamReader and StreamWriter

And they even use the using-statement! Which is hard to grasp quickly
(especially when the docs show it using a resource created before the
using statement block, which is strange since it is supposed to
destruct that object at the end of the block, but how can it do this
when the object it is *still in scope* after the using statement
block!?)
At the end of the using block the Dispose method is called
which will release all unmanaged resources. It is not
"destructed".

Arne
Mar 2 '07 #4
Most of the File and FileStream class' methods deal with arrays of bytes, so
one can assume that File is good for binaries. StreamReader/Writer can read
and write strings as well as bytes, so it's useful when working with text
files, especially large ones.

File's methods can read and write text from and to a file, but they do it
from a pre-allocated buffer or from a pre-allocated array of strings. And
they process the whole file at once. When you need to read a huge text file,
you can allocate a gigabyte-size string and read into it using File's
method. But would you prefer that to multiple calls to
StreamReader.ReadLine() ? With streams you can process large files and not
require lots of memory.

"Zytan" <zy**********@yahoo.comwrote in message
news:11**********************@v33g2000cwv.googlegr oups.com...
>I have installed the Visual C# 2005 Code Snippets, and the snippets
for file handling use StreamReader and StreamWriter, instead of
System.IO.File.*. VB 2005 code snippets don't use these. Why are
they suggesting the use of these classes instead of the fundamental
File methods? Are they better? I thought code snippets were supposed
show things in the easy / simple way.

What do you guys think? What should a beginner learn to do when
learning to read / write files?

Zytan

Mar 2 '07 #5
Thus wrote Zytan,
I have installed the Visual C# 2005 Code Snippets, and the snippets
for file handling use StreamReader and StreamWriter, instead of
System.IO.File.*. VB 2005 code snippets don't use these. Why are
they suggesting the use of these classes instead of the fundamental
File methods? Are they better? I thought code snippets were supposed
show things in the easy / simple way.
At the end of the day, you're always dealing with either a TextReader/TextWriter
or a Stream. Many of File's methods are convenience APIs that wrap or produce
streams and writers. It's mostly a matter of taste.
Cheers,
--
Joerg Jooss
ne********@joergjooss.de
Mar 2 '07 #6
At the end of the using block the Dispose method is called
which will release all unmanaged resources. It is not
"destructed".
Ok, I am thinking that destructed = dispose. What is the difference?
When I write a destructor, and it is run, this is the object being
destructed, right?

http://msdn2.microsoft.com/en-us/library/yh598w02.aspx
shows this example:

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}

It seems to me that font2 can still be used after the using statement
block. So what happens? Is the object destructed / disposed (sorry,
I don't know the difference), and font2 = null?

Zytan

Mar 2 '07 #7
File's methods can read and write text from and to a file, but they do it
from a pre-allocated buffer or from a pre-allocated array of strings. And
they process the whole file at once. When you need to read a huge text file,
you can allocate a gigabyte-size string and read into it using File's
method. But would you prefer that to multiple calls to
StreamReader.ReadLine() ? With streams you can process large files and not
require lots of memory.
Ah, so this is the difference. For me, I think whatever files I'll be
reading, I need them in memory all at once. So, it shouldn't matter.
For example, I could use:

string[] s = System.IO.File.ReadAllLines(path);

And, yes, it means s now stores the entire file, all at once, into
memory. But, I think this is ok for small files.

Thanks for the explanation, this is exactly what I wanted to know.

Zytan

Mar 2 '07 #8
At the end of the day, you're always dealing with either a TextReader/TextWriter
or a Stream. Many of File's methods are convenience APIs that wrap or produce
streams and writers. It's mostly a matter of taste.
Ok, thanks. So, I'll do it my way, and if I ever need to handle a
file as a stream of bytes (I don't think I do), I'll look into the
StreamReader/Writer.

Zytan

Mar 2 '07 #9
Zytan <zy**********@yahoo.comwrote:
At the end of the using block the Dispose method is called
which will release all unmanaged resources. It is not
"destructed".

Ok, I am thinking that destructed = dispose. What is the difference?
When I write a destructor, and it is run, this is the object being
destructed, right?
Well, it's being finalized. It *could* still survive, if something
during finalization promotes it - but generally, the object is about to
be garbage collected.

Being *disposed*, however, is very different - that's just calling the
Dispose method. After Dispose has been called, an object *may* still be
perfectly usable, and disposing of it doesn't affect garbage
collection, although calling Dispose will often suppress the finalizer
if there is one (because finalizers generally do the same thing).
http://msdn2.microsoft.com/en-us/library/yh598w02.aspx
shows this example:

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}

It seems to me that font2 can still be used after the using statement
block. So what happens? Is the object destructed / disposed (sorry,
I don't know the difference), and font2 = null?
font2 still refers to the same object, it's just that Dispose() has
been called on it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 2 '07 #10
Ok, I am thinking that destructed = dispose. What is the difference?
When I write a destructor, and it is run, this is the object being
destructed, right?

Well, it's being finalized. It *could* still survive, if something
during finalization promotes it - but generally, the object is about to
be garbage collected.
Ok, so in C#, there are no desrtuctors. They are called
'finalizers'? I can see the method name is Finalize.
Being *disposed*, however, is very different - that's just calling the
Dispose method. After Dispose has been called, an object *may* still be
perfectly usable, and disposing of it doesn't affect garbage
collection, although calling Dispose will often suppress the finalizer
if there is one (because finalizers generally do the same thing).
So, Dispose will not call Finalize, since they usually do the same
thing. So what happens when the object goes out of scope? Doesn't
Finalize get called?
Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}
It seems to me that font2 can still be used after the using statement
block. So what happens? Is the object destructed / disposed (sorry,
I don't know the difference), and font2 = null?

font2 still refers to the same object, it's just that Dispose() has
been called on it.
Ah, so font2 isn't null. It refers to the object. But, it's an
object that cannot be used since, it's been all but finalized?
Something seems very wrong with that.

The using statement forces Dispose to be called. But going out of
scope doesn't?
Why not just use blank braces { Object x; } so when the last } is hit,
doesn't x.Dispose get called, the same as if the braces were part of
the using statement?

Zytan

Mar 2 '07 #11
Zytan <zy**********@yahoo.comwrote:
Ok, I am thinking that destructed = dispose. What is the difference?
When I write a destructor, and it is run, this is the object being
destructed, right?
Well, it's being finalized. It *could* still survive, if something
during finalization promotes it - but generally, the object is about to
be garbage collected.

Ok, so in C#, there are no desrtuctors. They are called
'finalizers'? I can see the method name is Finalize.
Yup, although they're generally written with the destructor-like
syntax. You should very, very rarely need one though - only when you
*directly* hold unmanaged resources. If you only have a reference to
something else which holds unmanaged resources (e.g. a Stream) then
just implementing IDisposable is enough. Allow the Stream itself to
clean up on finalization if nothing else has cleaned it up by then.
Being *disposed*, however, is very different - that's just calling the
Dispose method. After Dispose has been called, an object *may* still be
perfectly usable, and disposing of it doesn't affect garbage
collection, although calling Dispose will often suppress the finalizer
if there is one (because finalizers generally do the same thing).

So, Dispose will not call Finalize, since they usually do the same
thing.
In fact, the finalizer usually calls Dispose.
So what happens when the object goes out of scope? Doesn't
Finalize get called?
No. The finalizer will be called *at some point* after the object is
eligible for finalization, i.e. when there are no more references to
it. There's no guarantee when that will be, or even necessarily whether
it will happen (e.g. during application termination).
It seems to me that font2 can still be used after the using statement
block. So what happens? Is the object destructed / disposed (sorry,
I don't know the difference), and font2 = null?
font2 still refers to the same object, it's just that Dispose() has
been called on it.

Ah, so font2 isn't null. It refers to the object. But, it's an
object that cannot be used since, it's been all but finalized?
Something seems very wrong with that.
It may or may not be usable - it depends on the implementation of
Dispose. Most of the time, it's not usable, and you would rarely use
the code pattern you showed - normally you declare the variable in the
using statement itself.
The using statement forces Dispose to be called. But going out of
scope doesn't?
Correct.
Why not just use blank braces { Object x; } so when the last } is hit,
doesn't x.Dispose get called, the same as if the braces were part of
the using statement?
No, x.Dispose doesn't get called, and neither does the finalizer
automatically - not at the point at which the variable falls out of
scope. Bear in mind that by then, there may be other references to the
same object (because x could have been passed to methods, etc). .NET
doesn't do reference counting, due to both the performance penalty and
the problem of cyclic references.

..NET has no deterministic resource clean-up - you need to do it
yourself, but the using statement makes life a lot simpler than it
would otherwise be.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 2 '07 #12
Hi,

"Zytan" <zy**********@yahoo.comwrote in message
news:11**********************@p10g2000cwp.googlegr oups.com...
>
http://msdn2.microsoft.com/en-us/library/yh598w02.aspx
shows this example:

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}
IMO even as the above may be a valid construction is not the best example,
shame that it's in MSDN , it should have been written like:
using ( Font font2 = new Font("Arial", 10.0f) )
{
// use font2
}


--
Ignacio Machin
machin AT laceupsolutions com
Mar 2 '07 #13
http://msdn2.microsoft.com/en-us/library/yh598w02.aspx
shows this example:
Font font2 = new Font("Arial", 10.0f);
using (font2)
{
// use font2
}

IMO even as the above may be a valid construction is not the best example,
shame that it's in MSDN , it should have been written like:

using ( Font font2 = new Font("Arial", 10.0f) )
{
// use font2
}
It is the second example MSDN shows. The first one is like yours.
And yes, this 2nd one is why it is so confusing to me. Maybe it would
have been best if C# didn't support it.

Zytan

Mar 2 '07 #14
Yup, although they're generally written with the destructor-like
syntax. You should very, very rarely need one though - only when you
*directly* hold unmanaged resources. If you only have a reference to
something else which holds unmanaged resources (e.g. a Stream) then
just implementing IDisposable is enough. Allow the Stream itself to
clean up on finalization if nothing else has cleaned it up by then.
Well, I was going to open a file for logging, and close the file at
the program's end. So, i thought I needed a finalizer. I mean, the
file doesn't close itself, does it? Or is that what Dispose is
precisely for, and perhaps it implements this. It's hard to say from
a newcomer's perspective if I have direct management of the resource
or not, such as opening / closing a file.
So what happens when the object goes out of scope? Doesn't
Finalize get called?

No. The finalizer will be called *at some point* after the object is
eligible for finalization, i.e. when there are no more references to
it. There's no guarantee when that will be, or even necessarily whether
it will happen (e.g. during application termination).
Yes, I knew about multiple references, I guess I was asking this in
terms of that being the only reference. I know C# removes the need
for me to worry about cleaning up. But, what's confusing is for
things NOT like classes and arrays, but files that I think I am
supposed to be the one manually telling it to close.
It may or may not be usable - it depends on the implementation of
Dispose. Most of the time, it's not usable, and you would rarely use
the code pattern you showed - normally you declare the variable in the
using statement itself.
Yes, I can follow I can not used the variable inside of the using
statement itself since it goes out of scope, but dealing with a
variable whose Dispose method has been automatically called, but still
is in scope, is confusing.
The using statement forces Dispose to be called. But going out of
scope doesn't?

Correct.
Right, i should know that C# doesn't guarantee when any object is
cleaned up, since the GC does it on its own clock. Which is the
reason using-statement exists, for things that must be cleaned up
right then and there.
No, x.Dispose doesn't get called, and neither does the finalizer
automatically - not at the point at which the variable falls out of
scope. Bear in mind that by then, there may be other references to the
same object (because x could have been passed to methods, etc). .NET
doesn't do reference counting, due to both the performance penalty and
the problem of cyclic references.
Yes, again, I knew about the multiple reference possibility. So,
using-statement just forces Dispose to be called at the end } where a
normal end } just says to the GC "you can clean this up when you
like" (provided there are no other references).

Zytan

Mar 2 '07 #15
Zytan <zy**********@yahoo.comwrote:
Yup, although they're generally written with the destructor-like
syntax. You should very, very rarely need one though - only when you
*directly* hold unmanaged resources. If you only have a reference to
something else which holds unmanaged resources (e.g. a Stream) then
just implementing IDisposable is enough. Allow the Stream itself to
clean up on finalization if nothing else has cleaned it up by then.

Well, I was going to open a file for logging, and close the file at
the program's end. So, i thought I needed a finalizer. I mean, the
file doesn't close itself, does it? Or is that what Dispose is
precisely for, and perhaps it implements this. It's hard to say from
a newcomer's perspective if I have direct management of the resource
or not, such as opening / closing a file.
You should close the file directly yourself, when the application is
terminating.
So what happens when the object goes out of scope? Doesn't
Finalize get called?
No. The finalizer will be called *at some point* after the object is
eligible for finalization, i.e. when there are no more references to
it. There's no guarantee when that will be, or even necessarily whether
it will happen (e.g. during application termination).

Yes, I knew about multiple references, I guess I was asking this in
terms of that being the only reference. I know C# removes the need
for me to worry about cleaning up. But, what's confusing is for
things NOT like classes and arrays, but files that I think I am
supposed to be the one manually telling it to close.
Exactly. .NET removes the need for you to worry about cleaning up
*memory*, but not other resources.
It may or may not be usable - it depends on the implementation of
Dispose. Most of the time, it's not usable, and you would rarely use
the code pattern you showed - normally you declare the variable in the
using statement itself.

Yes, I can follow I can not used the variable inside of the using
statement itself since it goes out of scope, but dealing with a
variable whose Dispose method has been automatically called, but still
is in scope, is confusing.
There are some cases where it's useful. For instance, even after you've
called Dispose on a MemoryStream, you can still call ToByteArray.
The using statement forces Dispose to be called. But going out of
scope doesn't?
Correct.

Right, i should know that C# doesn't guarantee when any object is
cleaned up, since the GC does it on its own clock. Which is the
reason using-statement exists, for things that must be cleaned up
right then and there.
Exactly.
No, x.Dispose doesn't get called, and neither does the finalizer
automatically - not at the point at which the variable falls out of
scope. Bear in mind that by then, there may be other references to the
same object (because x could have been passed to methods, etc). .NET
doesn't do reference counting, due to both the performance penalty and
the problem of cyclic references.

Yes, again, I knew about the multiple reference possibility. So,
using-statement just forces Dispose to be called at the end } where a
normal end } just says to the GC "you can clean this up when you
like" (provided there are no other references).
Well, the brace doesn't even do that really - the garbage collector
knows when a variable can last be used, and can collect an object even
when it's still in scope (in release mode). For instance:

object x = new object();
// Some code which uses x
// Point A
// Code which doesn't use x

At point A, if the garbage collector kicks in, it can garbage collect
the object referred to by x (assuming there are no other references)
because it knows the object can't be used by anything else.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 3 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: andrewcw | last post by:
OK I am half way there - I can manipulate the stream without the byte issue like this - but is this the way to push the new values back into the stream & write out the stream without resorting to...
4
by: Astronomically Confused | last post by:
using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; class HttpProcessor { private Socket s;
9
by: ShadowOfTheBeast | last post by:
Hi, I have got a major headache understanding streamReader and streamWriter relationship. I know how to use the streamreader and streamwriter independently. but how do you write out using the...
13
by: mloichate | last post by:
I must read a very heavy-weight text plain file (usually .txt extension) )and replace a given character with another given character in all text inside the file. My application was working pretty...
7
by: Daniel | last post by:
I have an winform application that uses System.IO.StreamReader and Serializer.Deserialize to load some data from a file, if any error is detected in the file a new file should be written to the...
16
by: vvenk | last post by:
Hello: When I use either one to read a Text file, I get the same result. The length of the string that the file's content has been written into is the same. However, if the file is binary,...
11
by: LucaJonny | last post by:
Hi, I've got a problem using StreamReader in VB.NET. I try to read a txt file that contains extended characters and theese are removed from the line that is being read. I've read a lot of...
5
by: Rob | last post by:
Hi, I have a VB.Net application that parses an HTML file. This file was an MS Word document that was saved as web page. My application removes all unnecessary code generated by MS Word and does...
0
by: rajana | last post by:
Dear All, We have Ansi file with german characters (Ä / Ø) , We are using Streamreader to read the contents of the file. But Readline() not able to read the German characters. We tried all...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.