Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream/StreamWriter in .NET Core 1.1 have no Close() method

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?

like image 428
James L. Avatar asked Nov 19 '16 08:11

James L.


People also ask

How to write a single line in a file using streamwriter?

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.

What is the use of close method in streamwriter?

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.

What is System Io stream writer close?

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.

How to manipulate files using FILESTREAM in Java?

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);


1 Answers

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
like image 169
Kamil T Avatar answered Sep 19 '22 09:09

Kamil T