You currently have JavaScript disabled on your browser.

This website uses JavaScript, and This page needs JavaScript activated to work correctly.

Please active JavaScript on your browser and then refresh this page.

File I/O



Microsoft Visual Studio's .NET classes provides several different out-of-the-box methods for reading and writing data to and from text files. In this blog post I would like to discuss a couple of the common approaches available and provide some code examples that I prefer using.

Before you can call and use the .NET file input output functions, you must add the following code to the very top of the class file that you want to use the functions in:

 
using System.IO;


ReadAllText

The ReadAllText() function is available within the File class that is located in the System.IO .NET library, and it offers a quick and simple way to read the entire content of a text file into a single string variable with one simple function call, with no need to open, cycle, and close the text file itself, since those tasks are done for you automatically by the ReadAllText() function. Afterwards that string variable can be processed however you see fit. The following example demonstrates this:

 
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // read entire content of a text file and return it as a single string
            string tempText = File.ReadAllText("C:\\temp\\dataFile.txt");
    
            // TODO : do something with this text variable
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}

However a problem with the ReadAllText() function is that it reads the entire contents of the target text file into memory all at once, and it returns the contents as a single string, which can take up a lot of RAM memory, especially is the text file is large. Plus, being a single string can make it a little more difficult to process.



ReadLines

The ReadLines() function is available within the File class that is located in the System.IO .NET library, and it offers a quick and simple way to read all lines from a text file into a string array with one simple function call, with no need to open, cycle, and close the text file itself, since those tasks are done for you automatically by the ReadLines() function. Afterwards that string array can then be cycled through and processed line by line. The following example demonstrates this:

 
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // read all lines of a text file and return it as a string array
            string[] lines = File.ReadLines("C:\\temp\\dataFile.txt");
    
            // loop through the string array
            foreach(string line in lines)
            {
                // TODO : do something with this line of text
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}

However one problem with the ReadLines() function is that it reads the entire contents of the target text file into memory all at once, and it returns the contents as a string array, which can take up a lot of RAM memory, especially is the text file is large.



StreamReader

Alternatively, and preferred, we can use the StreamReader class, which is available in the System.IO .NET library, which gives us much more control over the text file as we read it.

In the following code example, the StreamReader class is used to open, read, and then close text data from a text file. The path of the text file is passed to the StreamReader constructor to automatically open the file. The ReadLine() method then reads a single line of text from the file, and then increments the file pointer to the next line as it loops through the file via the while loop. Once the ReadLine() method returns a null reference, then it is believed to have reached the end of the text file and exits the while loop. Afterwards the text file is closed, which releases its resources to C#'s garbage collector:

 
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Pass the file path and file name to the StreamReader constructor
            StreamReader sr = new StreamReader("C:\\temp\\dataFile.txt");
	
            // First we read the first line of text
            string line = sr.ReadLine();
	
            // Then we continue to read each line until we reach the end of the file
            while (line != null)
            {
                // Read the next line		
                line = sr.ReadLine();
		
                // TODO : do something with this line of text
            }
	
            // close the file
            sr.Close();
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}

With the StreamReader class approach, we not only reduce the amount of memory required by the program to read and cycle through the contents of a text file, but we also gain speed, allowing the program to execute a little bit faster.



WriteAllText

A quick and simple way to write text file is to use the WriteAllText() function of the File class, which is available in the System.IO .NET library. With the WriteAllText() function, if the target text file already exists then it will be overwritten with the new text data written into it.

In the following code example, the WriteAllText() function is used to open, write, and then close text data into a text file. The path of the text file is passed to the method as a function argument, along with the string value that you wish to write into the file. The WriteAllText() function handles opening, writing to, and then closing the file for you automatically:

 
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Create a text string
            string writeText = "Hello World!"; 
            
            // Create a file and write the content of writeText to it
            File.WriteAllText("filename.txt", writeText);
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}


StreamWriter

To have the most control over writing data to a text file, we can use the StreamWriter class, which is available in the System.IO .NET library. With the StreamWriter class, if the target text file already exists then it will be overwritten with the new text data written into it.

In the following code example, the StreamWriter class is used to open, write, and then close text data into a text file. The path of the text file is passed to the StreamWriter constructor to automatically open the file. The WriteLine() method then writes a single line of text into the file. Once we use the WriteLine() method to write all of the desired lines of text into the text file, we then close the text file:

 
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Pass the file path and file name to the StreamWriter constructor
            StreamWriter sw = new StreamWriter("C:\\temp\\dataFile.txt");
    
            // Write a line of text
            sw.WriteLine("Hello World!!");
    
            // Write a second line of text
            sw.WriteLine("From your favorite program");
    
            // close the file
            sw.Close();
        }
        catch(Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}


Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


grayStargrayStargrayStargrayStargrayStar  Be the first to rate this post

User Comments






TJDivisions© 2022