C# StreamWriter and StreamReader Example


Program

using System;
using System.IO;

namespace IO_Samples
{
    class StreamWriterAndReader
    {
        public static void Main()
        {
            string[] names = new string[] { "Pawan", "Tharun",                                                        "Karthikeyan""Akash"
                                            "Ramkumar","Abinesh",
                                            "Partha","Rampranav"};

            using (StreamWriter sw = new                                                        StreamWriter(@"C:\TrainerSNA\Trainees.txt"))
            {
                foreach (string s in names)
                {
                    sw.WriteLine(s);
                }
            }
            Console.WriteLine("File has been created successfully.
                                \nPress any key to view the contents");
            Console.ReadKey();
           
            //Read and show each line from the line
            using (StreamReader sr = new                                                        StreamReader(@"C:\TrainerSNA\Trainees.txt"))
            {
                string line = "";
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }

            Console.ReadKey();
        }
    }
}

Output

File has been created successfully.
Press any key to view the contents

<<If you press any key, the following output will be displayed>>

Pawan
Tharun
Karthikeyan
Akash
Ramkumar
Abinesh
Partha
Rampranav

No comments:

Post a Comment