Skip to content

Reading and Writing External Data (C# Console Application)

External data: using text files to store data.

We will create a console application that will let us display text from, and save data to, an external data file. After we walk through how to read in data and write it back out, there is an example of how you could build a simple menu to access a file's information.

Screenshots in this walk through are of the free applications Visual Studio and SciTE. If you want to use the same applications you can find links in the post Free Programming Development Options.

Reading External Data

New Project

Create a new C# Console Application. If you are using Visual Studio there will be a Debug folder within your project directory. For this walk through we'll keep our text file in that folder.

If you are unsure where Visual Studio saves your files, look at the location option in the New Project dialog box. It will show you the path to your Visual Studio Projects folder.

External Data: New project example
New project example

Once you have your project, navigate to the Debug folder.

External Data: File path to the Debug folder
File path to the Debug folder

Text File

Create a new text file and save it as "data.txt". You can use any text editor you like, just make sure that the file is saved with the extension ".txt". Write some text inside so we'll have something to show when we pull content from it.

External Data: Example text file
Example text file

Using Directives

We'll need only two using directives for this program: System and System.IO.

using System; 
using System.IO;

We won't need the other directives that Visual Studio automatically adds to the console template. You can delete the extras.

System.IO

We are including the System.IO namespace because it contains types that allow reading and writing to files. Our example is simple, and only utilizes a few of the many options the namespace provides. After you create the example below, read the documentation at MSDN and try adding code to create and move through directories and sub-directories.

Console.ReadKey()

We want to keep the window from closing automatically, so add the ReadKey method inside of Main. You can use any of the following options:

  • Console.Read();
  • Console.ReadKey();
  • Console.ReadLine();

Code Example

Since this is a short example, we'll add our code to the Main method. If this was a larger project we would want to structure our code better, with the majority of our code outside of the Program.cs file.

Your code should look something like this example:

using System;
using System.IO;

namespace ExternalData
{
    class Program
    {
        static void Main()
        {
            Console.ReadKey();
        }
    }
}

Variables

Our next step is to add a variable to hold the file name. Set the value to "data.txt".

string DataFile = "data.txt";

Add another variable to hold the text that we will read in. I'm initializing mine with the string "[Empty File]".

string Content = "[Empty File]";

Test your code to make sure everything works. If you have any errors, compare your code to the example below.

using System;
using System.IO;

namespace ExternalData
{
    class Program
    {
        static void Main()
        {
            string DataFile = "data.txt";
            string Content = "[Empty File]";

            Console.Read();
        }
    }
}

File Class Methods

System.IO namespace has a class, File, with two methods we'll use to read in content: Exists and ReadAllText.

  • Exists(String): Determines whether the specified file exists.
  • ReadAllText(String): Opens a text file, reads all lines of the file, and then closes the file.

Before we read in data, we can check to make sure a specific file exists.

if (File.Exists(DataFile))
{
    Content = File.ReadAllText(DataFile, "");
}
Default value for Content variable can show the file is empty
Default value for Content variable

When the value of the variable Content is later written to the console window, it will show either the data that was read in from the external file, or the default string that indicates the file is empty ("[Empty File]").

After the external data is read in, write it to the console window.

Console.WriteLine(Content);

Test your code. If you have content in your data.txt file, you should see it displayed in the console window.

using System;
using System.IO;

namespace ExternalData
{
    class Program
    {
        static void Main(string[] args)
        {
            string DataFile = "data.txt";
            string Content = "(Empty File)";

            if (File.Exists(DataFile))
            {
                Content = File.ReadAllText(DataFile);
            }

            Console.WriteLine(Content);
            Console.ReadKey();
        }
    }
}
Data from external text file written to the console window
Data from external text file written to the console window

Writing Data to External File

Now that you have an example of reading in data from an external file, we can make an example of writing data to a text file with the File class method WriteAllText.

If the target file already exists, it will overwrite the contents. If the file doesn't exist, it will create a new file and write the string passed in to it. Finally it will close the file.

We'll be using the method definition that takes two arguments.

WriteAllText(String, String)

The two strings expected are the file name we are saving the data to, and what we want to write to the file. We have these pieces of information saved in our two variables DataFile and Content.

File.WriteAllText(DataFile, Content);

Unsecure Data

The data being stored and read is just text. It isn't protected or encrypted, and someone could open up the text file and edit it.

Reading from, and writing to, an external file is fine for data that doesn't need to be secured. For sensitive information you would want a different way of storing external data.

Menu Example

A quick menu example. Allows display and/or editing of a file's contents.

Example application with menu
Example application with menu
Example application with menu
Example application with menu


using System;
using System.IO;

namespace ExternalData
{
    class Program
    {
        public static string DataFile = "data.txt";
        public static string Content = "(Empty File)";
        public static string Input = "";
        public static bool Run = true;
        public static int Choice = 0;

        static void ColorText(string Message)
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.BackgroundColor = ConsoleColor.White;
            Console.WriteLine(Message);
            Console.ResetColor();
        }

        static void Main(string[] args)
        {
            Console.Title = "Reading and Writing Data to External File";

            while (Run == true)
            {
                Menu();
            }
        }

        static void Menu()
        {
            string Input = "";
            int Choice = 0;

            Console.WriteLine("\n\n\n\n\n------------------------------------------");
            Console.WriteLine(" 1) Read Content 2) Update Content 3) Exit");
            Console.WriteLine("------------------------------------------");

            Input = Console.ReadLine();
            Choice = Convert.ToInt32(Input);

            if (Choice == 1)
            {
                Console.Clear();
                if (File.Exists(DataFile))
                {
                    ColorText("\n\nThe file contents are:");
                    Content = File.ReadAllText(DataFile);
                }
                Console.WriteLine(Content);
            }
            else if (Choice == 2)
            {
                Console.Clear();
                ColorText("\n\nEnter new content and press enter to save it:");
                Input = Console.ReadLine();
                Content = Input;

                ColorText("\nConfirm that file contents will be replaced.\nType Y or N:");
                
                Input = Console.ReadLine();
                Input = Input.ToLower();

                if (Input == "y")
                {
                    File.WriteAllText(DataFile, Content);
                    ColorText("File updated.");
                }
                else
                {
                    ColorText("File not updated.");
                }
            }
            else
            {
                Run = false;
            }
        }
    }
}