253

I have a piece of code here that breaks if the directory doesn't exist:

System.IO.File.WriteAllText(filePath, content);

In one line (or a few lines), is it possible to check if the directory leading to the new file doesn't exist and if not, to create it before creating the new file?

I'm using .NET 3.5.

3

6 Answers 6

482

To Create

(new FileInfo(filePath)).Directory.Create() before writing to the file.

....Or, if it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
6
  • 8
    Elegant solution as it handles situations that require creation of nested folders. Commented May 8, 2017 at 20:57
  • Thank you! I saw stackoverflow.com/questions/9065598, but I wanted to start with the absolute path to a file, and didn't want to deal with splitting the path. Now I know that you can access the Directory from the FileInfo instance.
    – Johann
    Commented Jan 23, 2019 at 22:04
  • Is there an async way to do this? Commented Apr 10, 2019 at 18:48
  • 1
    I suppose you could do it with Task.Run(() => );.
    – Don
    Commented Apr 12, 2019 at 17:58
  • @JoePhillips, you could use WriteAllTextAsync Commented Jul 28, 2021 at 14:38
117

You can use following code

  DirectoryInfo di = Directory.CreateDirectory(path);
2
47

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:

Directory.CreateDirectory(Path.GetDirectoryName(filePath))

1

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

-1

You can use File.Exists to check if the file exists and create it using File.Create if required. Make sure you check if you have access to create files at that location.

Once you are certain that the file exists, you can write to it safely. Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.

Additional information for basic file I/O concepts.

1
  • I initially mis-read your question that you wanted to write to a file that may not exist. The concepts are essentially the same for File and Directory IO though.
    – hitec
    Commented Jun 2, 2010 at 6:24
-1

var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

var file = new FileInfo(filePath);

file.Directory.Create(); If the directory already exists, this method does nothing.

var sw = new StreamWriter(filePath, true);

sw.WriteLine(Enter your message here);

sw.Close();

Not the answer you're looking for? Browse other questions tagged or ask your own question.