Writing Files

Learn how to encode text into byte arrays and write data to files using the FileStream class.

The FileStream instance implements the IDisposable interface, so we must release the unmanaged resources after we are done using the instance. In this lesson, we will look at how to write data to a file and read it back.

Encode and decode

To write data to a file, we must convert it to a byte array. The specific means of converting a data type to a byte[] object varies depending on the nature of what we will store. Each file type has a specific format. For instance, we can encode text strings using UTF-8 or ASCII. 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 string into an array of bytes: