Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Write To A File C#

Using FileStream and StreamWriter class in System.IO namespace, users can create files and write contents.  See the example below. 

 

 
using System;
using System.IO;

namespace Com.Example.Csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //write a txt file
            WriteToFile("This is a test","test_txt","txt");
            //write a csv file
            WriteToFile("A,B,C,D","test_csv","csv");
        }

        public static void WriteToFile(String value, String filename,String fileExtention)
        {
            //opening txt file
            var file = new FileStream(filename+"."+fileExtention, FileMode.OpenOrCreate);
            var sw = new StreamWriter(file);

            //writing to the file
            sw.WriteLine(value);
            //closing file
            sw.Close();
        }
    }
}

Run the above code and check the created files "test_txt.txt" and "test_csv.csv".