Create a file from a path, creating subdirectories if they not exists

Solved using a little bit of code:

private static void EnsureDirectoryExists(string filePath) 
{ 
  FileInfo fi = new FileInfo(filePath);
  if (!fi.Directory.Exists) 
  { 
    System.IO.Directory.CreateDirectory(fi.DirectoryName); 
  } 
}

Sorry for this really newbie post... Thank you all! :-)


Another option if just want to create a folder/directory if it does not exist is to simply do this in C#:

// using System.IO;
if (!Directory.Exists(destination))
{
    Directory.CreateDirectory(destination);
}

No, they don't seem to - you'll get a DirectoryNotFoundException, I believe from all three.

You need to do something like a Directory.CreateDirectory(path) first.

EDIT:

For a bit more of a full solution which starts with a path including filename, try:

    Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

    TextWriter writer = new StreamWriter(fullPath);
    writer.WriteLine("hello mum");
    writer.Close();

But bear in mind you'll need some error handling too, so that the writer always gets closed (in a 'finally' block).

Tags:

.Net

File