How to create a new file using the path?

Let's say I need to create a new file whose path is ". \ A \ bb \ file.txt". Folder a and bb may not exist. How to create this file in C # in which folders a and bb are automatically created if they do not exist?

+5
source share
3 answers

This will create a file along with folders a and bb if they do not exist.

FileInfo fi = new FileInfo(@".\a\bb\file.txt");
DirectoryInfo di = new DirectoryInfo(@".\a\bb");
if(!di.Exists)
{
    di.Create();
}

if (!fi.Exists) 
{
    fi.Create().Dispose();
}
+9
source

Try the following:

string file = @".\aa\b\file.txt";
Directory.CreateDirectory(Path.GetDirectoryName(file));
using (var stream = File.CreateText(file))
{
    stream.WriteLine("Test");
}
+5
source

Try the following:

new DirectoryInfo(Path.GetDirectoryName(fileName)).Create();
+1
source

All Articles