Advertisements

How to create a file in C#

There are a few ways to create a file in C#. This post documents 3 ways to do that:

  1. Via the System.IO.FileInfo class
  2. Via the System.IO.File class
  3. Via the System.IO.FileStream class

Create a file using System.IO.FileInfo

using System;
using System.IO;

public class CreateFileWithFileInfo
{
    public static void Main() 
    {
        // Creates a file named techcoil.txt in the same directory as
        // the executing binary.
        FileInfo fileInfo = new FileInfo("techcoil.txt");
        FileStream fStream = fileInfo.Create();
        fStream.Close();
    }
}

Behaviour of code snippet

  • If file does not exist, a new one will be created.
  • If file exists, it will be overwritten.
  • If file exists and is currently opened by another process, a System.IO.IOException will be thown.

Create a file using System.IO.File class

using System;
using System.IO;

public class CreateFileWithFile
{
    public static void Main() 
    {
        // Creates a file named techcoil.txt in the same directory as
        // the executing binary.
        FileStream fStream = File.Create("techcoil.txt");
        fStream.Close();
    }
}

Behaviour of code snippet

  • If file does not exist, a new one will be created.
  • If file exists, it will be overwritten.
  • If file exists and is currently opened by another process, a System.IO.IOException will be thown.

Create a file using System.IO.FileStream class

public class CreateFileWithFileStream
{
    public static void Main() 
    {
        // Creates a file named techcoil.txt in the same directory as
        // the executing binary.
        FileStream fStream = File.Create("techcoil.txt");
        fStream.Close();
    }
}

Behaviour of code snippet

  • If file does not exist, a new one will be created.
  • If file exists, it will be overwritten.
  • If file exists and is currently opened by another process, a System.IO.IOException will be thown.

Related posts

Advertisements

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people.

Udemy deals
Advertisements