C#: Read a file and output to a second file

We can read the input file name and output file name from the command line.

For example, the name of our executable file is ReadFile.

From the command line, we can type in:

ReadFile test.txt test1.txt

test.txt will be the input file name and test1.txt will be the output file name.

We need to modify our previous program to take in 2 arguments in the command line.

using System;
using System.IO;

namespace ReadFile
    class Program
        static void Main(string[] args)
            string line;
            string inputFile = args[0];
            string outputFile = args[1];

            StreamReader file = new StreamReader(inputFile);
            StreamWriter fileOut = new StreamWriter(outputFile);

            while ((line = file.ReadLine()) != null)
                if (!string.IsNullOrEmpty(line))



From the above code, we can see that we read the input file using StreamReader class and the output file using StreamWriter class.

In this example, in line 19, if the line is Null or empty, it will not be read and ouput to the second file.  In a way, you can use this utility to remove empty lines in a text file.


Series Navigation<< C#: Read a file using while statement
C#: The do-while statement >>