Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

c# - how to use StreamWriter class properly?

I am using StreamWriter class for file operations, are there any problems in this code that I am not seeing?

Such as do I need to put it into a try catch finally block?

StreamWriter sr = new StreamWriter(streamFolder);
sr.Write(details);

File.SetAttributes(streamFolder, FileAttributes.Hidden);
sr.Close();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Whats wrong with your code? If some exception will occur before you close stream, then stream will stay open, and system resources will not be released:

StreamWriter sr = new StreamWriter(streamFolder);
sr.Write(details);
// some exception occurs here 
File.SetAttributes(streamFolder, FileAttributes.Hidden);
sr.Close();

So, you need to be sure, that stream will be closed. This could be achieved by try...finally block:

StreamWriter sr = new StreamWriter(streamFolder);

try 
{
   sr.Write(details);
   // some exception occurs here 
   File.SetAttributes(streamFolder, FileAttributes.Hidden);
}
finally
{
   sr.Close();
}

But StreamWriter implements IDisposable interface, so you can let C# compiler do it automatically for you by wrapping writer usage into using block:

using(StreamWriter sr = new StreamWriter(streamFolder)) 
{
   sr.Write(details);
   // some exception occurs here 
   File.SetAttributes(streamFolder, FileAttributes.Hidden);
}

This code will be compiled as:

StreamWriter sr = new StreamWriter(streamFolder);

try 
{
   sr.Write(details);
   // some exception occurs here 
   File.SetAttributes(streamFolder, FileAttributes.Hidden);
}
finally
{
   if (sr != null)
      sr.Dispose();
}

The only difference between manual implementation is null-check and method Dispose is called instead of Close. But actually when you call Close() or Dispose() same code will be executed:

this.Dispose(true);
GC.SuppressFinalize(this);

You can read more on Dispose method implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...