Home Programs Create a File in C#

Create a File in C#

In this example we show you how to create a new file in C#

Example

We use the Create() function the file is created and the content is written to the file. We then display a message on the screen to say that the file has been created.

We also open the text file and write the same message to it

using System;
using System.IO;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string myfile = @"J:\csharp\testfile.txt";
            using (FileStream fs = File.Create(myfile))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("File has been Created");
                fs.Write(info, 0, info.Length);
            }
            using (StreamReader sr = File.OpenText(myfile))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
            Console.Read();
        }
    }
}

 

You may also like