I'm using .net core 1.1, previously when I was with .net framework, I usually call Close()
on FileStream
or any Stream after I finished the stream operations, but the FileStream
class in .net core 1.1 doesn't have Close method, I found Dispose()
but don't know if it's the equivalent. Anyone care to let me know the right way to correctly close with the new FileStream/StreamWriter
class in .net core?
The StreamWriter is mainly used for writing multiple characters of data into a file. After initializing the FileStream object, we also initialized the StreamWriter object using the FileStream object. Then we used the WriteLine method to write a single line of data into the file. We then closed the StreamWriter and then the FileStream.
This implementation of Close calls the Dispose method passing a true value. You must call Close to ensure that all data is correctly written out to the underlying stream. Following a call to Close, any operations on the StreamWriter might raise exceptions. If there is insufficient space on the disk, calling Close will raise an exception.
System. IO Stream Writer. Close Method System. IO Closes the current StreamWriter object and the underlying stream. The current encoding does not support displaying half of a Unicode surrogate pair. The following code example demonstrates the Close method. This method overrides Stream.Close.
It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare. FileStream fileObj = new FileStream (file Name/Path, FileMode.field, FileAccess.field, FileShare.field);
Implementing IDisposable
means that you can use a using
statement, which will implicitly call the Dispose()
method, thus closing the stream.
Use
using (StreamWriter sw = new StreamWriter(path))
{
// your logic here
} // here Dispose() is called implicitly and the stream is closed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With