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?
Asked
Active
Viewed 2.9k times
3 Answers
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