473,412 Members | 5,361 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,412 software developers and data experts.

StreamReader.close and StreamWriter.close

Hi,

In the MSDN the sample doesn't use the close() method. But I know that
in most languages you do need to use the close() method after reading
and writing to a file.

from MSDN:

public static void Main()
{
string path = @"c:\temp\MyTest.txt";

try
{
if (File.Exists(path))
{
File.Delete(path);
}

using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}

using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}",
e.ToString());
}
}

does the "Using" replaces the needing for Close() method?

Feb 18 '07 #1
7 9763
<Er********@gmail.comwrote:
In the MSDN the sample doesn't use the close() method. But I know that
in most languages you do need to use the close() method after reading
and writing to a file.
<snip>
does the "Using" replaces the needing for Close() method?
Yes. "using" is equivalent to a try/finally block which calls Dispose()
in the finally block.

--
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
Feb 18 '07 #2
The simple answer to your question is yes the 'using' statement does replace
the need for a 'Close'...

check out the definitions of the using keyword in c#

http://www.c-sharpcorner.com/UploadF...Statement.aspx

The 2 classes you mention below - StreamReader & StreamWriter both implement
the IDisposable interface and you can use any class that implements this
interface in a 'using' statement.

These particular classes call 'Close' on the underlying stream object when
the Dispose method is called by the 'using' statement.

A 'using' statement is often called a try - catch - finally block, as in the
variable inside the 'using' statement is automatically wrapped into it's own
try - catch - finally block and the Dispose mehtod of the IDisposable
interface is always called in the finally statement.

HTH

Ollie Riches

<Er********@gmail.comwrote in message
news:11**********************@k78g2000cwa.googlegr oups.com...
Hi,

In the MSDN the sample doesn't use the close() method. But I know that
in most languages you do need to use the close() method after reading
and writing to a file.

from MSDN:

public static void Main()
{
string path = @"c:\temp\MyTest.txt";

try
{
if (File.Exists(path))
{
File.Delete(path);
}

using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}

using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}",
e.ToString());
}
}

does the "Using" replaces the needing for Close() method?

Feb 18 '07 #3
Hi,

Jon Skeet [C# MVP] wrote:
<Er********@gmail.comwrote:
>In the MSDN the sample doesn't use the close() method. But I know that
in most languages you do need to use the close() method after reading
and writing to a file.

<snip>
>does the "Using" replaces the needing for Close() method?

Yes. "using" is equivalent to a try/finally block which calls Dispose()
in the finally block.
About that, a question: I have this (pseudo)code that I want to refactor
using the "using" clause:

StreamWriter writer = null;

try
{
// ...
}
catch ( Exception ex )
{
logger.Log( ex.Message );
}
finally
{
if ( writer != null )
{
writer.Close();
writer.Dispose();
}
}

How to code that with a "using"? How can I do something special in case
an Exception occurs?

Greetings,
Laurent
--
Laurent Bugnion [MVP ASP.NET]
Software engineering, Blog: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Feb 21 '07 #4
Laurent Bugnion [MVP] <ga*********@bluewin.chwrote:
About that, a question: I have this (pseudo)code that I want to refactor
using the "using" clause:
<snip>
How to code that with a "using"? How can I do something special in case
an Exception occurs?
Either put a try/catch within the using statement, or outside 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
Feb 21 '07 #5
Hi Jon,

Jon Skeet [C# MVP] wrote:
Laurent Bugnion [MVP] <ga*********@bluewin.chwrote:
>About that, a question: I have this (pseudo)code that I want to refactor
using the "using" clause:

<snip>
>How to code that with a "using"? How can I do something special in case
an Exception occurs?

Either put a try/catch within the using statement, or outside it.
Thanks. I thought of that already, just wanted to confirm. Question
though: The code would become something like:

using ( StreamWriter writer = new StreamWriter( ... ) )
{
try
{
// ...
}
catch ( Exception ex )
{
logger.Log( ex.Message );

throw; // Is that correct??
}
}

I think that I shouldn't rethrow the Exception, is that correct? The
"using" clause is a try/finally, not try/catch/finally?

Thanks,
Laurent
--
Laurent Bugnion [MVP ASP.NET]
Software engineering, Blog: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Feb 22 '07 #6
Laurent Bugnion [MVP] wrote:
Hi Jon,

Jon Skeet [C# MVP] wrote:
>Laurent Bugnion [MVP] <ga*********@bluewin.chwrote:
>>About that, a question: I have this (pseudo)code that I want to
refactor using the "using" clause:

<snip>
>>How to code that with a "using"? How can I do something special in
case an Exception occurs?

Either put a try/catch within the using statement, or outside it.

Thanks. I thought of that already, just wanted to confirm. Question
though: The code would become something like:

using ( StreamWriter writer = new StreamWriter( ... ) )
{
try
{
// ...
}
catch ( Exception ex )
{
logger.Log( ex.Message );

throw; // Is that correct??
}
}

I think that I shouldn't rethrow the Exception, is that correct? The
"using" clause is a try/finally, not try/catch/finally?

Thanks,
Laurent
If you rethrow the exception or not depends on if you completely handled
it or not. If the code that called this method needs to know about the
exception, you should rethow it.

I haven't investigated if a using clause has a catch or not, but if it
has, it rethrows the exception. The point is that the using clause does
not consume exceptions.

--
Göran Andersson
_____
http://www.guffa.com
Feb 22 '07 #7
Hi,

Göran Andersson wrote:
If you rethrow the exception or not depends on if you completely handled
it or not. If the code that called this method needs to know about the
exception, you should rethow it.

I haven't investigated if a using clause has a catch or not, but if it
has, it rethrows the exception. The point is that the using clause does
not consume exceptions.
That confirms what I actually observed. Thanks.

Laurent
--
Laurent Bugnion [MVP ASP.NET]
Software engineering, Blog: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Feb 22 '07 #8

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

Similar topics

2
by: Joecx | last post by:
Using vb.net, I am using Streamreader to read a text file and searching for a line to delete, the I close the file and open it as a streamwriter so I can put the new file back to disk without the...
6
by: Jimbo | last post by:
After I read or write a file with streamreader and streamwriter and I close it with the Close method, does that automatically let go of the file so that any other process can modify it? In my...
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...
1
by: R.L. | last post by:
See the code below, var 'content ' is suppose to be "Hello!", not "". Who knows why? Thanks ---------------------------------------- string text = "hello!"; MemoryStream stream = new...
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...
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: 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
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.