Eric Sjöström Jennerstrand

Litium E-commerce, C#, .NET MAUI, Javascript, React, Azure, Git. .NET, Node and more!
Create file in C#

How to create a file in C#

To create a file in C#, all you need is one line. But unlike creating a directory, you have to check if the file exists. If you don’t check if the file exists, the first file will be overwritten. So if you run the line below 2 times, the first file will be overwritten.
The method Create or AppendAllText can be used to create all types of files. You just have to make sure the content is correct.

var path = "C:\\temp\\project1\\MyFirstFile.csv";
if (!File.Exists(path))
var path = "C:\\temp\\project1\\MyFirstFile.txt";
if (!File.Exists(path))
    File.AppendAllText(path, "Content that will be added in the file.");

Using the method Create or AppendAllText is the best and fastest way to create a file with content in C# and is widely used in my projects.

Check this post if you need to create a Directory in C#:
Or look at this post to write lines to a text file:

Source on files from Microsoft:

Check out these simple easy to read articles about add object to List, reverse for loops and for loops if you want som extra reading:

One thought on “How to create a file in C#

  • Thank you for sharing your info.
    2022-09-02 at 00:46

    Thank you for sharing your info. I really appreciate your efforts and I am waiting for your further
    write ups thank you once again.

Leave a Reply

Your email address will not be published. Required fields are marked *.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>