Search
Desktop

Create, Read, and Write a Text File

Published 1 min readBy Programming4us Editorial Team
If you tell .NET that you are opening a text file, the underlying stream is wrapped in a text decoder called StreamReader or StreamWriter that can translate between UTF-8 text and the raw bytes.

Here is a sample program that writes its command-line arguments to a text file that you specify and then reads it back:

class Program
{
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine(
"Usage: ConsoleToFile filename output1 output2 output3 ...");
return;
}
//write each command line argument to the file
string destFilename = args[0];
using (StreamWriter writer = File.CreateText(destFilename))
{
for (int i = 1; i < args.Length; i++)
{
writer.WriteLine(args[i]);
}
}
Console.WriteLine("Wrote args to file {0}", destFilename);

//just read back the file and dump it to the console
using (StreamReader reader = File.OpenText(destFilename))
{
string line = null;
do
{
line = reader.ReadLine();
Console.WriteLine(line);
} while (line != null);
}
}
}


Note

For this and all succeeding code examples in this chapter, make sure you have using System.IO; at the top of your file, as it will not always be explicit in every code sample.


Note

Files are shared resources, and you should take care to close them when done to return the resource back to the operating system. This is done using the Dispose Pattern,  “Memory Management.” The using statements in the preceding code sample ensure that the files are closed at the end of each code block, regardless of any exceptions that occur within the block. You should consider this a best practice that you should always follow whenever possible.