File IO simple

In this simple example of File IO, we have a createFile method which is taking an argument for firstName, lastName and the requested fileName.

The createFile method is using the fileName argument in adjacent to the System.IO.TextWriter class in order to create the file and applying the Write/WriteLine methods in order to process the strings we would like to write in the file.

The readFile method is used simply to print out the contents of the created file to the debugging window using the same System.IO.TextWriter class.

    class Program
    {
        static void Main(string[] args)
        {
            //("Thomas","Eames","one.txt");
            readFile("one.txt");
            Console.ReadKey();
        }

        private static void createFile(string firstName, string lastName, string fileName)
        {
            TextWriter w = new StreamWriter(fileName);
            w.Write(String.Join(" ", firstName, lastName, DateTime.Now,"\n"));
            w.WriteLine("-------------------------------------------------\n");
            for(int i=1; i<10; i++)
            {
                w.WriteLine($"{i} X 12 = {i * 12}");
            }
            w.WriteLine("");
            w.WriteLine("Thanks for using my program");
            w.Close();

        }

        private static void readFile(string fileName)
        {
            TextReader r = new StreamReader(fileName);
            string line = r.ReadLine();
            while (line != null)
            {
                Console.WriteLine(line);
                line = r.ReadLine();
            }
            r.Close();
        }
    }

No Comments Yet