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.FileInfo
class - Via the
System.IO.File
class - 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.