Coder Perfect

How can I make a directory if one doesn’t already exist in order to create a file?


I have some code that will fail if the directory does not exist:

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

Is it possible to verify if the directory leading to the new file doesn’t exist and, if it doesn’t, create it before creating the new file in one line (or a few lines)?

.NET 3.5 is the framework I’m working with.

Asked by Diskdrive

Solution #1

(filePath) -> new FileInfo(filePath) -> new FileInfo(filePath) Directory. Before writing to the file, call Create().

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);

Answered by Don

Solution #2

The code below can be used.

  DirectoryInfo di = Directory.CreateDirectory(path);

Answered by Ram

Solution #3

As @hitec mentioned, you must confirm that you have the proper permissions; if you do, you may use this line to verify the directory’s existence:


Answered by willvv

Solution #4

Create the following extension to the native FileInfo class for an elegant way to relocate your file to an empty directory:

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)


Then use the MoveTo extension, which is completely new:

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

Check out the documentation for the Methods extension.

Answered by MiguelSlv

Solution #5

You can make use of File. Exists to see if the file already exists and if not, create it with File. If necessary, create. Check to see if you have permission to create files at that location.

You can securely write to the file after you’re sure it exists. However, as a precaution, you should put your code in a try…catch block and catch any exceptions that function might throw if things don’t go as intended.

Additional information on the fundamentals of file I/O.

Answered by hitec

Post is based on