StreamWriter Class is more popular in File Handling and it is simple helpful in writing text data in file. It is simple to use and provides complete set of constructors and methods to work.

It is very simple to writer data into a text file using StreamWriter Class and most of the beginners prefer to use this class in writing file. You can understand it with the below programming example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace StreamWriter_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\csharpfile.txt";
            using (StreamWriter writer = new StreamWriter(file))
            {
                writer.Write("Hello");
                writer.WriteLine("Hellow StreamWriter Class");
                writer.WriteLine("How are you!");
            }
            Console.WriteLine("Data Saved Successfully!");
            Console.ReadKey();
        }
    }
}
Now open D:\csharpfile.txt and you will see data is saved.
Some times you need to save variable data in a file. These variable data might be output of your program, log details, exception error etc. In the next programming I will show you how can you save variable data in a file using StreamWriter Class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace StreamWriter_VariableData
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\csharpfile.txt";
            int a, b, result;
            a = 5;
            b = 10;
            result = a + b;
            using (StreamWriter writer = new StreamWriter(file))
            {
                writer.Write("Sum of {0} + {1} = {2}", a, b, result);
            }
            Console.WriteLine("Saved");
            Console.ReadKey();
        }
    }
}

Now open the D:\csharpfile.txt again and you will see the following text in a file.

Sum of 5 + 10 = 15

Leave a Reply

Your email address will not be published. Required fields are marked *