C# - If A Folder Does Not Exist, Create It - Stack Overflow
C# - If A Folder Does Not Exist, Create It - Stack Overflow
Asked 8 years, 4 months ago Active 18 days ago Viewed 801k times
I use a FileUploader control in my application. I want to save a file in a specified folder. Now I want, if this folder does not exist, to first create it,
and then save my file to this folder. If the folder already exists, then just save the file in it.
725 How I can do this?
c# asp.net directory
85
edited Feb 27 '19 at 13:26 asked Jan 30 '12 at 14:42
Ola Ström Tavousi
775 1 6 23 11.4k 14 44 64
@JoeBlow - Ha - should have specified which answer is incorrect - now the page is even more confusing. (Did he change the accepted answer? or did he not?
OMG!) ;-) – Bartosz Jun 3 '16 at 12:15
I ended up here while looking for other things, but it's amazing how many people are fighting to contradict each other with their own version of the same story.
Microsoft authored the .NET Framework and the MSDN. Whether the correct behavior is respected by other implementers, such as Mono, is irrelevant to the
correctness of the behavior described in MSDN. Oh, and Mono does the correct thing also, so where's the argument? – monkey0506 Aug 19 '17 at 20:16
Possible duplicate of How do I create directory if it doesn't exist to create a file? – brichins Oct 10 '17 at 22:03
But, you don't need to check if it exists first. From the docs
1243
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory
already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
edited Mar 26 '19 at 20:58 answered Jan 30 '12 at 14:49
John Cummings Mark Peters
1,258 3 13 25 14.2k 2 16 15
32 For the .NET Framework 4.5 version the actual quotation is "If the directory already exists, this method does not create a new directory, but it returns a
DirectoryInfo object for the existing directory." – Igor Kustov Jan 16 '14 at 14:07
25 and yet the microsoft code example contradicts itself by checking if the directory exists first... – ecoe Oct 8 '14 at 11:54
1 So we have to check if it exists or not? If we check and then also the CreateDirectory method check again, we make the check two times... and AFAIK
filesystem operation are expensive – Giox Feb 18 '17 at 17:20
3 @Muflix like this - create a file for example "FILENAME" on a directory but don't give it any extension. Then try calling Directory.Exists("FILENAME") will return
false, as it should because there is no such directory. Now if you call CreateDirectory("FILENAME") it will fail miserably as it should because there is already
"something" with that name there. Hope that makes sense. – Otávio Décio Mar 14 '17 at 12:38
1 WRONG! I You MUST check if the folder exists. I just Identified that this method has a serious problem. If you don't check for existence of the folder, the
Folder handle will leak unless you specifically release it. We used this example in an application that processes millions of folders. Every time this method was
called, the application retained the file handle to the directory. After several hours, the Corporate Network NAS had millions of File Handles open on the
folders. Updating to include the check free's the handle – soddoff Baldrick Aug 16 '19 at 1:19
if(!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
159 No need to check if folder exists. Read the manual carefully. – bazzilic Jul 12 '13 at 7:52
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
31 Checking and creating is not atomic. The above code smells, there is a race condition. You should better just unconditionally create the directory, and catch a
FileExists (or whatever the C# equivalent) exception in case the function is designed to throw one. – Jo So Sep 20 '13 at 15:28
6 Like others have pointed out, there is no need for the call to Exists and it actually creates a new failure condition. – Ed S. Jul 1 '14 at 23:35
3 @MartinSmith: Then just create the directory. Don't check for existence before. That is not only shorter. It also doesn't give a false impression of what the API
of System.IO.Directory.CreateDirectory is. (And it is faster, but probably that doesn't matter) – Jo So Sep 18 '14 at 10:05
Of course, you can also write using System.IO; at the top of the source file and then just write Directory.CreateDirectory("my folder"); every
time you want to create a folder.
Directory.CreateDirectory Explains how to try and to create the FilePath if it does not exist
Directory.Exists Explains how to check if a FilePath exists. However, you don't need this as CreateDirectory will check for you.
28
edited Oct 21 '19 at 14:49 answered Jan 30 '12 at 14:45
jeroenh
22.7k 9 64 96
@Tavousi this functions provided by jeroenh would be good start ;) – Allan Chua Jan 30 '12 at 14:46
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
none of the msdn documentation links seem to be working at the moment, even via msdn search... – jeroenh Jul 29 '15 at 18:06
the links are fine now – Anand Mar 1 '18 at 20:58
This enables race conditions, see the accepted answer. – ComFreek Aug 21 '19 at 8:30
You can create the path if it doesn't exist yet with a method like the following:
27 using System.IO;
8 @bazzilic yes, but it reveals intent. I don't have to guess (or know for sure) how the API handles this. Anyone who reads this code will know for sure what will
happen. – Dennis Traub Jul 12 '13 at 8:12
4 In multithreaded environments (such as the state of a filesystem) you only ever have the choice of locking or try-and-catch. The snippet above has a race
condition. The function might throw a FileExists Exception (or whatever it's called in C#) – Jo So Sep 20 '13 at 15:26
9 "it reveals intent" -- This is not a good justification. You could just write a comment in the code. – Jim Balter Jul 29 '14 at 1:21
This method will create folder if not exist and do nothing if exists
15 Directory.CreateDirectory(path);
15 try
{
if (!Directory.Exists(path))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
8 This is a good answer, but, according to the MSDN documentation, "Any and all directories specified in path are created, unless they already exist or unless
some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing." So, you don't
really need the call to Directory.Exists(path). – ken Jan 30 '12 at 14:48
2 That's true but that's also an assumtion so it's always best to check rather than to assume regardless of what MSDN Says.. – MethodMan Jan 30 '12 at 14:53
6 @DJ KRAZE, I believe MSDN unless it has been proven to be wrong. You recommend the opposite - ignore what MSDN says and add extra (unnecessary)
checks into your code. Where do you draw the line? – Polyfun Jan 30 '12 at 15:29
1 ShellShock nowhere do I say ignore.. this is a persumtious statement I am saying it's better to not assume than to assume.. read what i have stated once again..
thanks – MethodMan Jan 30 '12 at 17:01
3 @DJKRAZE nobody's assuming anything. It is written in plain english in the manual that check is not necessary. – bazzilic Jul 12 '13 at 7:54
using System.IO
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
if (!Directory.Exists(yourDirectory))
14 Directory.CreateDirectory(yourDirectory);
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
13 }
3 CreateDirectory already handles the check if the directory does not exists. – bergmeister Nov 16 '17 at 10:13
Following code is the best line(s) of code i use that will create directory if not present .
6 System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/temp/"));
If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory. >
CreateDirectory already handles the check if the directory does not exists. – bergmeister Nov 16 '17 at 10:13
@bergmeister ,Thanks .I just crossed checked .It really removed conditional check .Updated !! – UJS Nov 17 '17 at 3:21
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
Create new folder, given a parent folder's path:
Use below code. I used this code for file copy and create new folder.
if (!exists)
{
System.IO.Directory.CreateDirectory(folderLocation);
if (System.IO.File.Exists(fileToCopy))
{
MessageBox.Show("file copied");
System.IO.File.Copy(fileToCopy, newLocation, true);
}
else
{
MessageBox.Show("no such files");
}
}
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
answered Sep 13 '15 at 10:46
Lemon Kazi
3,006 2 23 47
Use this Code if folder is not presented under image folder or other folders
A fancy way is to extend the FileUpload with the method you want.
Add this:
-1
public static class FileUploadExtension
{
public static void SaveAs(this FileUpload, string destination, bool
autoCreateDirectory) {
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
if (autoCreateDirectory)
{
var destinationDirectory = new
DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.SaveAs(destination);
}
}
FileUpload file;
...
file.SaveAs(path,true);
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
The CreateDirectory is also used to create a sub directory. All you have to do is to specify the path of the directory in which this subdirectory will
be created in. The following code snippet creates a Mahesh subdirectory in C:\Temp directory .
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
// Create sub directory
if (!Directory.Exists(subdir))
{
Directory.CreateDirectory(subdir);
6 What is the point of encapsulating a method into what is essentially an exact copy, with only a slightly different name? You literally gain nothing from this. –
Krythic Feb 23 '18 at 3:14
Highly active question. Earn 10 reputation in order to answer this question. The reputation requirement helps protect this question from spam and non-answer
activity. By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.