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:
- Via the System.IO.FileInfoclass
- Via the System.IO.Fileclass
- Via the System.IO.FileStreamclass
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.
 Share
 Share
           Tweet
 Tweet
           Share
 Share
           Save
 Save