Search⌘ K
AI Features

Writing Files

Explore how to write text data to files in C# using FileStream and the Encoding class to convert strings into byte arrays. Understand the importance of properly disposing unmanaged resources with using blocks, and learn modern asynchronous methods like File.WriteAllTextAsync for efficient file writing.

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 ...