How do I create a file AND any folders, if the folders don't exist?
Solution 1
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!
Solution 2
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.
Solution 3
Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.
Solution 4
. 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.
Solution 5
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.
Related videos on Youtube
Pure.Krome
Just another djork trying to ply his art in this mad mad world. Tech stack I prefer to use: Laguage: C# / .NET Core / ASP.NET Core Editors: Visual Studio / VS Code Persistence: RavenDB, SqlServer (MSSql or Postgres) Source control: Github Containers: Docker & trying to learn K&'s Cloud Platform: Azure Caching/CDN: Cloudflare Finally: A Tauntaun sleeping bag is what i've always wanted spaces > tabs
Updated on February 02, 2021Comments
-
Pure.Krome over 3 years
Imagine I wish to create (or overwrite) the following file :-
C:\Temp\Bar\Foo\Test.txt
Using the File.Create(..) method, this can do it.
BUT, if I don't have either one of the following folders (from that example path, above)
- Temp
- Bar
- Foo
then I get an DirectoryNotFoundException thrown.
So .. given a path, how can we recursively create all the folders necessary to create the file .. for that path? If Temp or Bar folders exists, but Foo doesn't... then that is created also.
For simplicity, lets assume there's no Security concerns -- all permissions are fine, etc.
-
mateuscb over 9 yearspossible duplicate of saving a file and automatically create directories
-
Michael Freidgeim over 7 yearsPossible duplicate of If a folder does not exist, create it
-
Pure.Krome almost 14 yearsRemarks: Any and all directories specified in path are created ... ahh kewl! cheers :)
-
Pure.Krome almost 14 yearsI should downgrade this because of this line:
using Microsoft.VisualBasic;
Evil!! -
Gertjan almost 14 yearsFor Directory.CreateDirectory you do not need to see which part exists. It will create all directories needed (only thing to make sure is that the targeted directory does not exists already).
-
Gertjan almost 14 yearsI suggest removing the first line of you answer in that case since he doesn't need to check for each part from the root, just check the complete path and create it if it does not exist.
-
Tim Robinson almost 14 yearsYou can blindly call
Directory.CreateDirectory
without theDirectory.Exists
check first - it won't throw if the directory is already there. -
Christopher B. Adkins almost 14 years@Tim: Wasn't sure so I threw it in there anywho. Thanks for the info though.
-
Oded almost 14 years@Gertjan - answer updated... hope it meets your standards now ;)
-
Oliver almost 14 yearsAnd why is Microsoft.VisualBasic evil?? It's an assembly like anyone else in the .Net Framework.
-
Oliver almost 14 yearsAnd don't forget about
Path.GetDirectoryName(string path)
to get the directory from your full path -
Gertjan almost 14 years:) it does :) (it was not my point to prove you wrong or to offend you, but beginners can use any clarification in the answers)
-
Markive almost 14 yearsI suppose because your importing the namespace of a whole other language unnecessarily..?
-
Christopher B. Adkins almost 14 years@Oliver: There is a whole slew of functionality that goes along with the Directory and DirectoryInfo classes, but the code I gave was enough to give him a push in the right direction. I think the link also expands quite a bit.
-
PRR almost 14 years@Pure.Krome: Although my answer is off target, still do consider security and access control when accessing privileged resource. Never meant to overtake or complicate your question :)
-
sazr about 10 years*NOTE: the variable
path
should not contain the file name. So using the OP's examplepath
should beC:\Temp\Bar\Foo
. After callingDirectory.CreateDirectory(path);
you still need to callFile.Create("C:\Temp\Bar\Foo\Test.txt");
to create the file. -
Sameera R. over 8 yearspath without file name :)
-
Camilo Terevinto about 8 years"all directories and subdirectiories" Incorrect: it will create, at most, one directory and all the required subdirectories.
-
Alexei Levenkov over 5 yearsIf you are dealing with long path (256+) see stackoverflow.com/questions/5188527/…
-
Thomas Fritz over 3 yearsIt seems like the questioner wanted to create files rather than copy them.
-
Mehdi Dehghani over 3 years@ThomasFritz you are right, but still there some good info about working with files and folders in my answer, don't you think so? should I delete my answer?
-
Thomas Fritz over 3 yearsI don't think you have to delete your answer per se: While it may not answer the original question it is placed below a handful of answers which do just that. Instead, your answer serves as an introduction to a different topic, specifically how files are copied, which I don't mind a little variety among StackOverflow answers. What you can do - if you have the time - is to adjust the wording of your answer in a way so that it doesn't present itself like the most complete answer of them all, which I believe to be an overstatement.
-
Bartosz Wójtowicz over 3 yearsThis doesn't work as it would create also a directory with the file name.