Reputation: 35374
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?
Upvotes: 11
Views: 32349
Reputation: 12934
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();
}
Upvotes: 10
Reputation: 5070
Try this:
string file = @".\aa\b\file.txt";
Directory.CreateDirectory(Path.GetDirectoryName(file));
using (var stream = File.CreateText(file))
{
stream.WriteLine("Test");
}
Upvotes: 9
Reputation: 45101
Try this one:
new DirectoryInfo(Path.GetDirectoryName(fileName)).Create();
Upvotes: 1