Creating a File that the Path does not exists?
Solution 1
Try
Directory.CreateDirectory(@"C:\MyApp\MySubDir\Data")
http://www.devx.com/vb2themax/Tip/18678
Solution 2
Given that you've the full path (Folder + File name), the following code will ensure your required directory path exists (if it does not exist already)
FileInfo fileInfo = new FileInfo(fileFullPath);
if (!fileInfo.Exists)
Directory.CreateDirectory(fileInfo.Directory.FullName);
//create the file ...
Solution 3
below should also work
FileInfo fileInfo = new FileInfo(fileFullPath);
if (!fileInfo.Directory.Exists) fileInfo.Directory.Create()
work on directory of fileinfo, rather than static directory class
Solution 4
You will need to create the Directory first. It will create all of the subdirectories that don't exist within the path you send it. It's quite a powerful piece of functionality.
Directory.CreateDirectory(filePath);
If you don't know whether the directory exists or not you can use Directory.Exists. But not for this case as it would be pointless. MSDN states that CreateDirectory does nothing if the directory currently exists. But if you wanted to check existance of the directory for another reason you can use:
if(Directory.Exists(folder) == false)
{
//do stuff
}
Solution 5
Directory.CreateDirectory("path");
Related videos on Youtube
Comments
-
Athiwat Chunlakhan almost 2 years
I just can't get around this. I am able to create a file with
File.Create
...File.CrateText
and so on, only if the path exists. If it does not the file will not we written and returns an error. How do I create the path?-
Jerry Coffin about 11 yearspossible duplicate of How to create multiple directories from a single full path in C#?
-
-
Bdiem over 14 yearsAs this post mostlikely solves your problem here the additional MSDN information: msdn.microsoft.com/en-us/library/as2f1fez.aspx
-
Athiwat Chunlakhan over 14 yearsAnd how do we check if the path exists? or we just call this function.
-
Bdiem over 14 yearsREAD! MSDN Says: If the folder already exists, CreateDirectory does nothing.
-
Daniel Elkington over 5 yearsThis won't work if the filePath is a full path (folder + file name) - it'll annoyingly create a directory with the name of your desired file (eg if filePath is
pathTo\helloWorld.txt
it'll create a folder namedhelloWorld.txt
inside the folderpathTo
). -
Shambhu Kumar over 5 years@DanielElkington are you sure about that?
-
Daniel Elkington over 5 yearsI tested this the other day and that’s what happened. Ashraf Alam’s answer using the FileInfo class to split out the directory name worked. But if you know the path is only a directory then this will work.