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();
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:
So, you need to be sure, that stream will be closed. This could be achieved by
try...finallyblock:But StreamWriter implements IDisposable interface, so you can let C# compiler do it automatically for you by wrapping writer usage into
usingblock:This code will be compiled as:
The only difference between manual implementation is null-check and method
Disposeis called instead ofClose. But actually when you callClose()orDispose()same code will be executed:You can read more on Dispose method implementation.