Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a file AND any folders, if the folders don't exist?

People also ask

How do you create a directory if it does not exist in Java?

Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.

How create folder if not exist in PHP?

Methods: file_exists(): It is an inbuilt function that is used to check whether a file or directory exists or not. is_dir(): It is also used to check whether a file or directory exists or not. mkdir() : This function creates a directory.


To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.


DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
    Directory.GetCreationTime(path));

See this MSDN page.

Hope that helps out!


Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.


. given a path, how can we recursively create all the folders necessary to create the file .. for that path

Creates all directories and subdirectories as specified by path.

Directory.CreateDirectory(path);

then you may create a file.


You will need to check both parts of the path (directory and filename) and create each if it does not exist.

Use File.Exists and Directory.Exists to find out whether they exist. Directory.CreateDirectory will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.