Home > Articles > Programming > Windows Programming

Text File Access in the .NET Framework

  • Print
  • + Share This
Many apps need the ability to read from or write to text files. Peter Aitken explores .NET Framework tools that let you include this capability in your applications.
Like this article? We recommend

Like this article? We recommend

Most applications need to be able to read and write files. The .NET Framework provides classes that take most of the pain out of file access, but you still have to write the code that makes use of these classes. While a file is nothing more than a sequence of bytes, the .NET Framework distinguishes between two types of files based on how those bytes are handled:

  • Text files contain character data.
  • Binary files contain non-character data (graphics, numbers, and so on).

This article covers the fundamentals of text file access. I’ll cover binary file access in a future article.

Opening Text Files for Reading

Inputting text from a file is done with the StreamReader class. This class has a variety of specialized constructors, but the one you’ll need most often is as follows:

Dim sr As New StreamReader (filename)

This code opens the specified file by using the default UTF8 character encoding, which is the Unicode encoding used by Windows. This is just what you need almost all of the time. If you have to work with other encodings, you’ll use one of the other StreamReader constructors—refer to the documentation for the details.

Another way to create a StreamReader associated with a text file is to use the File class’s OpenText() method. File is a static class, so you don’t need to create an instance of it. Here’s what the code would look like:

Dim sr As StreamReader
sr = File.OpenText(filename)

The result is exactly the same as the other syntax:

Dim sr As New StreamReader(filename)

Both of these statements will cause an exception if the file is not found. Of course, if the user has selected the file by using a File Open dialog box, this shouldn’t be a problem, but I’ve gotten in the habit of always checking for the file first by using the File class’s FileExists() method:

If File.FileExists(filename) Then
 ’ File exists - open it.
 ’ File does not exist - display message to user.
End If

Speaking of exceptions, it’s essential that all of your file input and output code be enclosed in Try..Catch blocks. This is necessary because file access is fraught with so many potential problems, such as network outages and sharing violations.

Once you’ve finished reading from the file (covered in the next section), be sure to close the file, using the Close() method:

  • + Share This
  • 🔖 Save To Your Account