Program readerwriter.cs

Demonstrates use of StreamWriter and StreamReader objects 



using System;
using System.IO;

class Program {

    static void Main() {

        string input = string.Empty;
        string retrieved = string.Empty;

        while (input != "e") {
        
            input = PresentMenu();            

            switch (input) {

                case "w":

                    StreamWriter sw;
                    sw = File.CreateText("myfile.txt");
                    Console.WriteLine("\nEnter the text you wish to write to the file, then press Enter:\n");
                    input = Console.ReadLine().Trim();
                    sw.WriteLine(input);
                    sw.Close();
                    Console.WriteLine();
                    break;

                case "r":

                    StreamReader sr;
                    sr = File.OpenText("myfile.txt");
                    retrieved = sr.ReadLine();
                    sr.Close();
                    
                    Console.WriteLine("\nThe file contained the following line of text:\n");
                    
                    if (retrieved.Trim() == "") {
                        Console.WriteLine("The line of text in the file consisted of an empty string\n");
                    } else {
                        Console.WriteLine(retrieved + "\n");
                    }//endif
                    
                    break;

                default:
                    break;

            }//end switch statement

        }//wend



    }//end method Main()

    public static string PresentMenu() {

        string choice = string.Empty;

        Console.WriteLine("\nMENU\n");
        Console.WriteLine("W - Write text to the text file\n");
        Console.WriteLine("R - Read contents of the text file\n");
        Console.WriteLine("E - Exit program\n");
        choice = Console.ReadLine().Trim().ToLower();

        return choice;

    }

}//end class Program