Nam G VU
Nam G VU

Reputation: 35374

How to create new file with path?

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

Answers (3)

Amsakanna
Amsakanna

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

Jens Granlund
Jens Granlund

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

Oliver
Oliver

Reputation: 45101

Try this one:

new DirectoryInfo(Path.GetDirectoryName(fileName)).Create();

Upvotes: 1

Related Questions