Create Text File

.C# Create Text File


C# Create Text File

.Create Text File

"A C# program which writes the HTML lines for creating a test template page."

The program creates the HTML lines for a number of test questions and corresponding answers. The number of test questions is set by the constant NUMBER_OF_QUESTIONS.

The following C# features are used in the sample code:

  1. FileStream - FileStream exposes a stream around a file for read and write operations.
  2. TextWriter - TextWriter is an abstract class (do not instantiate) that provides members for writing to a stream
  3. StreamWriter - StreamWriter is designed for character output in a particular encoding (defaults to UTF8Encoding).


Create Text File

using System.IO;

namespace TestGeneration
{
    class Program
    {
        static void Main(string[] args)
        {

            // Number of test questions
            const int NUMBER_OF_QUESTIONS = 100;

            // Path to output file
            string filePath = @"c:\genfiles\test.txt";

            // Delete the file if it already exists.
            if (System.IO.File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            // Create the file
            using (FileStream fs = File.Create(filePath))
            using (TextWriter writer = new StreamWriter(fs))
            {
                // Questions
                for (int i = 1; i <= NUMBER_OF_QUESTIONS; i++)
                {
                    writer.WriteLine("<a id=\"{0}\"></a>", i);
                    writer.WriteLine("{0}.", i);
                    writer.WriteLine("<blockquote>");
                    writer.WriteLine("</blockquote>");
                    writer.WriteLine("<a href=\"#{0}a\">Answer</a>\r\n", i);
                }

                writer.WriteLine("< ***** End of Questions ****** >");

                // Answers
                for (int i = 1; i <= NUMBER_OF_QUESTIONS; i++)
                {
                    writer.WriteLine("<a id=\"{0}a\"></a>", i);
                    writer.WriteLine("{0}. Answer is: ", i);
                    writer.WriteLine("<br><a href=\"#{0}\">Back</a>\r\n", i);
                }
            }
        }
    }
}