Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
392 views

C# - If A Folder Does Not Exist, Create It - Stack Overflow

The document discusses how to create a folder if it does not exist before saving a file to that folder in C#. It provides multiple responses summarizing ways to check if a folder exists and create it using the System.IO.Directory class if it does not exist, including using the CreateDirectory method without first checking for existence. Later responses note potential issues with race conditions if existence is checked before creating.

Uploaded by

joao Westwood
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
392 views

C# - If A Folder Does Not Exist, Create It - Stack Overflow

The document discusses how to create a folder if it does not exist before saving a file to that folder in C#. It provides multiple responses summarizing ways to check if a folder exists and create it using the System.IO.Directory class if it does not exist, including using the CreateDirectory method without first checking for existence. Later responses note potential issues with race conditions if existence is checked before creating.

Uploaded by

joao Westwood
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

If a folder does not exist, create it

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

17 Answers Active Oldest Votes

As others have said, use System.IO.Directory.CreateDirectory

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

Use the below code as per http://forums.asp.net/p/1226236/2209871.aspx:

359 string subPath ="ImagesPath"; // your code goes here

bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

if(!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));

edited Sep 4 '14 at 19:01 answered Jan 30 '12 at 14:45


Francisco Noriega Ravia
9,886 10 45 70 8,932 3 26 38

41 Why not: if (!Directory.Exists(path_to_check)) Directory.CreateDirectory(path_to_check); – Dayan Mar 31 '13 at 17:31

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

Just write this line :

226 System.IO.Directory.CreateDirectory("my folder");

If the folder does not exist yet, it will be created.


If the folder exists already, the line will be ignored.

Reference: Article about Directory.CreateDirectory at MSDN

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.

edited Aug 6 '19 at 7:20 answered Aug 27 '14 at 4:47


Nicolas Raoul
52k 49 184 318

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;

private void CreateIfMissing(string path)


{
bool folderExists = Directory.Exists(Server.MapPath(path));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(path));
}

edited Jan 30 '12 at 14:53 answered Jan 30 '12 at 14:45


Dennis Traub
42.6k 7 76 94

6 Check if (!folderExists) is not needed. – bazzilic Jul 12 '13 at 7:52

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

answered Dec 30 '14 at 14:07


By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
Thakur Rock
435 4 6

You can use a try/catch clause and check to see if it exist:

15 try
{
if (!Directory.Exists(path))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}

edited Apr 26 '16 at 14:01 answered Jan 30 '12 at 14:45


Alan Guilfoyle MethodMan
352 4 11 16.8k 6 30 50

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

answered Jan 30 '12 at 14:46


BlackBear
19.4k 8 37 74

if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
13 }

edited Dec 15 '15 at 10:16 answered Dec 15 '15 at 9:50


Haris Kiran Solkar
11.2k 6 31 54 1,099 4 16 27

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. >

edited Jul 13 '18 at 12:54 answered Nov 25 '16 at 9:47


Sapnandu UJS
369 1 7 725 1 7 16

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:

5 string pathToNewFolder = System.IO.Path.Combine(parentFolderPath,


"NewSubFolder");
DirectoryInfo directory = Directory.CreateDirectory(pathToNewFolder);
// Will create if does not already exist (otherwise will ignore)

path to new folder given


directory info variable so you can continue to manipulate it as you please.

edited Jun 5 at 1:06 answered Aug 9 '18 at 11:02


BKSpurgeon
20.5k 8 76 61

Use below code. I used this code for file copy and create new folder.

0 string fileToCopy = "filelocation\\file_name.txt";


String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);

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

string createfolder = "E:/tmp/" + uId;


System.IO.Directory.CreateDirectory(createfolder);
0
answered Nov 21 '15 at 9:00
amit
249 3 6 18

Use this Code if folder is not presented under image folder or other folders

0 string subPath = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/");


bool exists = System.IO.Directory.Exists(subPath);
if(!exists)
System.IO.Directory.CreateDirectory(subPath);
string path = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/" +
OrderId + ".png");

answered Feb 12 at 6:39


Jogi
51 4

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

Then use it:

FileUpload file;
...
file.SaveAs(path,true);

answered Feb 22 at 0:00


MiguelSlv
7,927 3 55 105

string root = @"C:\Temp";

string subdir = @"C:\Temp\Mahesh";


-3
// If directory does not exist, create it.

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

edited Dec 20 '14 at 8:04 answered Dec 20 '14 at 7:46


Rizier123 uksp
54.5k 16 75 118 17 8

Derived/combined from multiple answers, implementing it for me was as easy as this:

-5 public void Init()


{
String platypusDir = @"C:\platypus";
CreateDirectoryIfDoesNotExist(platypusDir);
}

private void CreateDirectoryIfDoesNotExist(string dirName)


{
System.IO.Directory.CreateDirectory(dirName);
}

answered Oct 28 '15 at 18:40


B. Clay Shannon
24.3k 112 354 696

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.

You might also like