You are currently offline, waiting for your internet to reconnect

How to read a text file by using System.IO and Visual C#

This article was previously published under Q306777
For a Microsoft Visual Basic .NET version of this article, see 302309.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
  • System.IO
  • System.Collections
This step-by-step article shows you how to retrieve information from a text file (.txt), and then use an ArrayList class to display that information to the user.


Microsoft Visual C#

Reading text files in Visual C#

Opening and reading files for read access is an important part of input/output (IO) functionality, even if you do not need to write to the file in question. This example opens a file for reading, which is useful for reading text files but inappropriate for binary files. This example uses one of many methods that are available for opening the file.

Although many data structures are available to store information that is retrieved from the file, an ArrayList class is the easiest structure to use. To open and read from the file, this example uses objects from the System.IO namespace, specifically the System.IO.StreamReader class.

Note This sample requires some form of a text (.txt) file from which to read.

To load and read through a text file from Visual C#, follow these steps:
  1. Start Microsoft Visual Studio.
  2. Create a new Console Application in Visual C#. Visual Studio creates a Static Class for you, along with an empty Main() procedure.
  3. Verify that the project references at least the System namespace. Use the using statement on the System, System.IO, and System.Collections namespaces so that you are not required to qualify declarations from these namespaces later in your code. You must use these statements before any other declarations.
    using System;using System.IO;using System.Collections;					
  4. To open a file for reading, create a new instance of a StreamReader object, and pass the file's path into the constructor as follows:
    StreamReader objReader = new StreamReader("c:\\test.txt");					
  5. You must have a string variable in which to store each line of the file as you process. Because you will be adding these lines to an ArrayList, declare and create an object of that type, also.
    string sLine="";ArrayList arrText = new ArrayList();					
  6. There are several ways to read the file in, including the ReadToEnd method which reads in the entire file at once. However, for this example, you can use the ReadLine method to bring in the file one line at a time. When the end of the file is reached, this method returns a null, which provides a way for you to end your loop. As you read each line from the file, you can use the Add method of the ArrayList to insert the lines into your ArrayList class.
    while (sLine != null){	sLine = objReader.ReadLine();	if (sLine != null)		arrText.Add(sLine);}objReader.Close();					
  7. Use a For Each loop to write the contents of your newly filled ArrayList to the console as follows:
    foreach (string sOutput in arrText)	Console.WriteLine(sOutput);Console.ReadLine();					
  8. Save and run your code, which produces a listing of your file to the console.

Complete code listing

using System;using System.IO;using System.Collections;namespace TextFileReader_csharp{	/// <summary>	/// Summary description for Class1.	/// </summary>	class Class1	{		static void Main(string[] args)		{			StreamReader objReader = new StreamReader("c:\\test.txt");			string sLine="";			ArrayList arrText = new ArrayList();			while (sLine != null)			{				sLine = objReader.ReadLine();				if (sLine != null)					arrText.Add(sLine);			}                        objReader.Close();			foreach (string sOutput in arrText)				Console.WriteLine(sOutput);			Console.ReadLine();		}	}}				


There are several things to be aware of when you work with file I/O, including the following items:
  • Any time that you access a file, there is the possibility that the file that you are trying to read or write may not be on the system or may be in use.
  • This example reads the entire file into memory before it processes the file. You may encounter a situation in which the file is too large to be held in memory, or you may not have permissions to access the file.
Any of these situations cause an exception to be raised. It is always good practice to provide a try...catch block to handle these common issues.

Article ID: 306777 - Last Review: 08/28/2007 06:26:02 - Revision: 2.6

Microsoft Visual C# 2005, Microsoft Visual C# .NET 2002 Standard Edition, Microsoft Visual C# 2008 Express Edition

  • kbcollections kbhowtomaster kbio KB306777
>">">kTracking = 1; var varCustomerTracking = 1; var Route = "76500"; var Ctrl = ""; document.write(" g = 1; var Route = "76500"; var Ctrl = ""; document.write(" p;did=1&t=">