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 Response

  1. 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 *

This website uses cookies. By continuing to use this site, you accept our use of cookies.