Writing Files
Write to files without causing memory leaks.
We'll cover the following
Introduction
The FileStream
instance implements the IDisposable
interface, so we must release the unmanaged resources after we’re done using the instance. In this lesson, we’ll look at how to write data to a file and read it back.
Encode and decode
If we want to write something to a file, we must convert it to an array of bytes. The specific means of converting a data type to a byte[]
object varies depending on the nature of what we’ll store. Each file type has a specific format. For instance, we can encode text (string
objects) using UTF8 encoding, ASCII, and so on. Depending on the encoding type, the array of bytes and the contents of the file are both different.
If we want to write some text to a file, we can use the Encoding
class. It converts a .NET data type into an array of bytes:
string text = "Hello World!";
byte[] bytes = Encoding.UTF8.GetBytes(text);
Note: The
Encoding
class only works with text formats and text objects.
Write text
After we have a text encoded into a byte array, we can start writing it to a file stream (FileStream
object). As when we read from a file, we first create an instance of the FileStream
class:
using (var fileStream = new FileStream(fileName, FileMode.Create))
{
}
The FileMode.Create
ensures that we create a new file. If the file already exists, then it is overwritten.
Next, we use the Write()
method of the FileStream
object to write our byte array to the file:
fileStream.Write(bytes, 0, bytes.Length);
The bytes
, in our case, is the byte[]
object we want to write, 0
is the offset (from which position we should start writing), and bytes.Length
is the number of bytes we write. In this case, we write the whole byte array.
We can reverse the process to ensure that our text was written successfully:
Get hands-on with 1400+ tech skills courses.