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.
File.Create("C:\\temp\\project1\\MyFirstFile.txt");
var path = "C:\\temp\\project1\\MyFirstFile.csv";
if (!File.Exists(path))
{
File.Create(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#: https://www.jennerstrand.se/create-directory-in-c/
Or look at this post to write lines to a text file: https://www.jennerstrand.se/write-lines-to-a-text-file-in-c-sharp/
Source on files from Microsoft: https://docs.microsoft.com/en-us/dotnet/api/system.io.file?view=net-5.0
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:
https://www.jennerstrand.se/add-object-to-list-in-c-sharp.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.
https://www.jennerstrand.se/for-loop-in-c-sharp-simple.
Thank you for sharing your info.
Thank you for sharing your info. I really appreciate your efforts and I am waiting for your further
write ups thank you once again.