Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream Vs System.IO.File.WriteAllText when writing to files [closed]

Tags:

c#

.net

vb.net

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?

like image 480
Flood Gravemind Avatar asked Jun 29 '13 13:06

Flood Gravemind


People also ask

What does FileStream close () do?

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

What is System IO FileStream?

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.

What is the difference between FileStream and StreamWriter?

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.

Does WriteAllText overwrite?

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.


1 Answers

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:

  • Multiple inputs
  • Real time data from a memory/network 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);
}
like image 67
Mataniko Avatar answered Oct 17 '22 21:10

Mataniko