I have seen many examples/ tutorials about VB.NET or C#.NET where the author is using a FileStream
to write/read from a file. My question is there any benefit to this method rather than using System.IO.File.Read/Write
? Why are the majority of examples using FileStream
to when the same can be achieved using just a single line of code?
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
The FileStream is a class used for reading and writing files in C#. 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.
Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.
WriteAllText(String, String) Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
FileStream
gives you a little more control over writing files, which can be beneficial in certain cases. It also allows you to keep the file handle open and continuously write data without relinquishing control. Some use cases for a stream:
System.IO.File
contains wrappers around file operations for basic actions such as saving a file, reading a file to lines, etc. It's simply an abstraction over FileStream
.
From the .NET source code here is what WriteAllText
does internally:
private static void InternalWriteAllText(string path,
string contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, false, encoding))
sw.Write(contents);
}
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