939

I use a FileUploader control in my application. I want to save a file to a specified folder. If this folder does not exist, I want to first create it, and then save my file to this folder. If the folder already exists, then just save the file in it.

How can I do this?

Bob Kaufman
  • 12,864
  • 16
  • 78
  • 107
Tavousi
  • 14,848
  • 18
  • 51
  • 70
  • @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 03 '16 at 12:15
  • 1
    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
  • 2
    Possible duplicate of [How do I create directory if it doesn't exist to create a file?](https://stackoverflow.com/questions/2955402/how-do-i-create-directory-if-it-doesnt-exist-to-create-a-file) – brichins Oct 10 '17 at 22:03

16 Answers16

1498
Use System.IO.Directory.CreateDirectory.

According to the official ".NET" docs, you don't need to check if it exists first.

System.io   >   Directory   >   Directory.CreateDirectory

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.

        — learn.microsoft.com/dotnet/api/

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77
Mark Peters
  • 17,205
  • 2
  • 21
  • 17
  • 46
    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."](http://msdn.microsoft.com/en-us/library/54a0at6s%28v=vs.110%29.aspx) – Igor Kustov Jan 16 '14 at 14:07
  • 51
    and yet the microsoft code example contradicts itself by checking if the directory exists first... – ecoe Oct 08 '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
  • 1
    Except if you have a file with the same name as the directory. This will both indicate that Directory.Exists(path) is false and fail when calling CreateDirectory(path). – Otávio Décio Feb 19 '17 at 19:03
  • @OtávioDécio you mean file without an extension ? – Muflix Mar 14 '17 at 09:30
  • 6
    @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
  • 6
    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 01:19
  • 7
    @soddoffBaldrick You must be doing something terribly wrong in your code, because neither [Directory](https://referencesource.microsoft.com/#mscorlib/system/io/directory.cs) nor [DirectoryInfo](https://referencesource.microsoft.com/#mscorlib/system/io/directoryinfo.cs) do anything with handles. Eventually, Directory.Create boils down to a chain of calls to the Win32 CreateDirectory function, and that function, again, does not do anything with handles. Your handle leak is elsewhere. – Tom Lint Jun 02 '20 at 10:56
  • really @TomLint? I have pretty good evidence that it does exactly that. But I was always suspicious that the SAN's SMB implementation (non-windows) is the source of the issue - so you could be right. We never saw the issue in testing, but this was on a windows server. – soddoff Baldrick Jul 09 '20 at 05:25
  • 2
    @ecoe lol. I wouldn't say it contradicts itself, it just chooses to check if it exists, you're always free to do that (you may want to know if it exists and take different action, not want the existing DirectoryInfo object returning). – niico Jan 07 '21 at 01:27
  • 3
    `CreateDirectory()` **will happily create all the directories in a path.** No need to put it in a loop. – bbsimonbb Jan 18 '22 at 10:31
417

Use the below code as per How can I create a folder dynamically using the File upload server control?:

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));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravi Vanapalli
  • 9,805
  • 3
  • 33
  • 43
  • Sorry, I missed adding the link. – Ravi Vanapalli Jan 30 '12 at 14:52
  • http://totaldotnet.com/Tip/ShowTip22_UsePhysicalAppPath.aspx Server.MapPath vs PhysicalApplicationPath. Do you agree? – Jaime Feb 21 '13 at 15:40
  • 48
    Why not: if (!Directory.Exists(path_to_check)) Directory.CreateDirectory(path_to_check); – Dayan Mar 31 '13 at 17:31
  • 182
    No need to check if folder exists. Read the manual carefully. – bazzilic Jul 12 '13 at 07:52
  • 38
    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
  • 9
    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 01 '14 at 23:35
  • 1
    It's unnecessary but I don't see why it would cause a race condition or new failure condition. @JoSo As pointed out in the other comments if the directory is created after the check then the call to `CreateDirectory` does nothing anyway. – Martin Smith Sep 18 '14 at 09:44
  • 4
    @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
  • 1
    @JoSo - Nowhere does my comment dispute that. – Martin Smith Sep 18 '14 at 11:30
  • As bazzilic said read up on CreateDirectory! "Creates all directories and subdirectories in the specified path unless they already exist." taken from https://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory%28v=vs.110%29.aspx – Paul Zahra Oct 23 '15 at 08:09
  • Server is not defiened – Naitik Singhal Aug 05 '21 at 11:12
291

Just write this line:

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nicolas Raoul
  • 58,567
  • 58
  • 222
  • 373
31

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 it for you.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jeroenh
  • 26,362
  • 10
  • 73
  • 104
29

You can create the path if it doesn't exist yet with a method like the following:

using System.IO;

private void CreateIfMissing(string path)
{
  bool folderExists = Directory.Exists(Server.MapPath(path));
  if (!folderExists)
    Directory.CreateDirectory(Server.MapPath(path));
}
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • 8
    Check `if (!folderExists)` is not needed. – bazzilic Jul 12 '13 at 07:52
  • 10
    @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 08:12
  • 5
    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
  • 13
    "it reveals intent" -- This is not a good justification. You could just write a comment in the code. – Jim Balter Jul 29 '14 at 01:21
19

This method will create the folder if it does not exist and do nothing if it exists:

Directory.CreateDirectory(path);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thakur Rock
  • 515
  • 5
  • 7
19

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

  try
  {
    if (!Directory.Exists(path))
    {
       // Try to create the directory.
       DirectoryInfo di = Directory.CreateDirectory(path);
    }
  }
  catch (IOException ioex)
  {
     Console.WriteLine(ioex.Message);
  }
Alan Guilfoyle
  • 381
  • 4
  • 13
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • 9
    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). – qxn 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
  • 7
    @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 07:54
  • 1
    The one benefit of a check is that it creates an opportunity for meaningful logging. But certainly not needed for the basic mechanics. – VoteCoffee Apr 20 '18 at 12:23
  • It could fail for other reasons, e.g. a virus checker kicking in at the worst possible time. – Peter Mortensen Nov 18 '20 at 03:32
14
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
Haris
  • 12,120
  • 6
  • 43
  • 70
Kiran Solkar
  • 1,204
  • 4
  • 16
  • 29
13
using System.IO

if (!Directory.Exists(yourDirectory))
    Directory.CreateDirectory(yourDirectory);
BlackBear
  • 22,411
  • 10
  • 48
  • 86
10

Create a new folder, given a parent folder's path:

        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 information variable so you can continue to manipulate it as you please.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BenKoshy
  • 33,477
  • 14
  • 111
  • 80
9

The following code is the best line(s) of code I use that will create the directory if not present.

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
UJS
  • 853
  • 1
  • 10
  • 16
3

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

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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jogi
  • 81
  • 4
0

Use the below code. I use this code for file copy and creating a new folder.

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");
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lemon Kazi
  • 3,308
  • 2
  • 37
  • 67
-1

A fancy way is to extend the FileUpload with the method you want.

Add this:

public static class FileUploadExtension
{
    public static void SaveAs(this FileUpload, string destination, bool autoCreateDirectory) { 

        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);
MiguelSlv
  • 14,067
  • 15
  • 102
  • 169
  • But class `FileUploadExtension` is not used anywhere(?). – Peter Mortensen Nov 18 '20 at 03:44
  • What do you mean by *"extend the FileUpload"*? – Peter Mortensen Nov 18 '20 at 03:44
  • @PeterMortensen https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods. In my solution, the SaveAs method have another version with a second parameter that tells to create or not the directory. The name of the class that holds the new method has to be different from the class that i am extending. That may cause confusion, but that is the way it is. – MiguelSlv Nov 18 '20 at 13:27
-2
string root = @"C:\Temp";

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

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

// Create sub directory

if (!Directory.Exists(subdir))
{

Directory.CreateDirectory(subdir);

}
Rizier123
  • 58,877
  • 16
  • 101
  • 156
uksp
  • 27
  • 8
-5

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

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

private void CreateDirectoryIfDoesNotExist(string dirName)
{
    System.IO.Directory.CreateDirectory(dirName);
}
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 7
    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 03:14
  • @Krythic One reason for the encapsulation may be documentation. It is unclear that the directory is only created if it does not exist from the `CreateDirectory` statement alone. But as someone in this thread had mentioned, he could just write a comment to explain that. – Lukas Feb 28 '23 at 15:49