473,587 Members | 2,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

StreamReader.cl ose and StreamWriter.cl ose

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\MyTes t.txt";

try
{
if (File.Exists(pa th))
{
File.Delete(pat h);
}

using (StreamWriter sw = new StreamWriter(pa th))
{
sw.WriteLine("T his");
sw.WriteLine("i s some text");
sw.WriteLine("t o test");
sw.WriteLine("R eading");
}

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

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

Feb 18 '07 #1
7 9772
<Er********@gma il.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.co m>
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********@gma il.comwrote in message
news:11******** **************@ k78g2000cwa.goo glegroups.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\MyTes t.txt";

try
{
if (File.Exists(pa th))
{
File.Delete(pat h);
}

using (StreamWriter sw = new StreamWriter(pa th))
{
sw.WriteLine("T his");
sw.WriteLine("i s some text");
sw.WriteLine("t o test");
sw.WriteLine("R eading");
}

using (StreamReader sr = new StreamReader(pa th))
{
while (sr.Peek() >= 0)
{
Console.WriteLi ne(sr.ReadLine( ));
}
}
}
catch (Exception e)
{
Console.WriteLi ne("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********@gma il.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*********@bl uewin.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.co m>
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*********@bl uewin.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*********@bl uewin.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
2418
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 line that I deleted. Can someone tell me how I can do this without having to close the file first before switching to streamwriter, because closing...
6
19992
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 form, I read from a small configuration file with streamreader and close it with streamreader.Close(). In this same event, when I open it for...
4
8725
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
4579
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 streamwriter, what you have read into a streamReader? and also can someone explain how they work in simple terms -- The Matrix Insurrection
1
4665
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 MemoryStream(); StreamWriter streamWriter = new StreamWriter(stream, Encoding.ASCII); streamWriter.Write(text);
13
3959
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 well with this below shown code (code placed in a buttonclick event after selecting the file in a normal OpenFileDialog): ...
16
2076
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, FileGet gets me the correct content while StreamReader gives me a truncated string. Can somebody advise me why? Should I be using BinaryReader...
11
31694
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 articles about ANSI encoding like this http://support.microsoft.com/default.aspx?scid=kb;en-us;889835 but System.Text.Encoding.Default don't work!!
5
6864
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 some custom formatting needed by my client. I use a StreamReader to read in the file...regular expressions to parse and clean up the file...and a...
0
7918
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7843
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8206
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7967
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6621
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5392
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.