7

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

Nam G VU
  • 33,193
  • 69
  • 233
  • 372

3 Answers3

10

This will create the file along with the 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();
}
Amsakanna
  • 12,254
  • 8
  • 46
  • 58
8

Try this:

string file = @".\aa\b\file.txt";
Directory.CreateDirectory(Path.GetDirectoryName(file));
using (var stream = File.CreateText(file))
{
    stream.WriteLine("Test");
}
Jens Granlund
  • 4,950
  • 1
  • 31
  • 31
1

Try this one:

new DirectoryInfo(Path.GetDirectoryName(fileName)).Create();
Oliver
  • 43,366
  • 8
  • 94
  • 151