If a folder does not exist, create it

993,527

Solution 1

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

But, you don't need to check if it exists first. From the documentation:

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.

Solution 2

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

Solution 3

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.

Solution 4

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.

Solution 5

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));
}
Share:
993,527
Tavousi
Author by

Tavousi

Updated on July 08, 2022

Comments

  • Tavousi
    Tavousi almost 2 years

    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?

    • Bartosz
      Bartosz almost 8 years
      @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!) ;-)
    • monkey0506
      monkey0506 over 6 years
      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?
    • brichins
      brichins over 6 years
  • Allan Chua
    Allan Chua over 12 years
    @Tavousi this functions provided by jeroenh would be good start ;)
  • ken
    ken over 12 years
    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).
  • Ravi Vanapalli
    Ravi Vanapalli over 12 years
    Sorry, I missed adding the link.
  • MethodMan
    MethodMan over 12 years
    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..
  • Polyfun
    Polyfun over 12 years
    @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?
  • MethodMan
    MethodMan over 12 years
    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
  • Jaime
    Jaime about 11 years
    totaldotnet.com/Tip/ShowTip22_UsePhysicalAppPath.aspx Server.MapPath vs PhysicalApplicationPath. Do you agree?
  • Dayan
    Dayan about 11 years
    Why not: if (!Directory.Exists(path_to_check)) Directory.CreateDirectory(path_to_check);
  • bazzilic
    bazzilic almost 11 years
    Check if (!folderExists) is not needed.
  • bazzilic
    bazzilic almost 11 years
    No need to check if folder exists. Read the manual carefully.
  • bazzilic
    bazzilic almost 11 years
    @DJKRAZE nobody's assuming anything. It is written in plain english in the manual that check is not necessary.
  • Dennis Traub
    Dennis Traub almost 11 years
    @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.
  • Jo So
    Jo So over 10 years
    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
    Jo So over 10 years
    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.
  • Igor Kustov
    Igor Kustov over 10 years
  • Ed S.
    Ed S. almost 10 years
    Like others have pointed out, there is no need for the call to Exists and it actually creates a new failure condition.
  • Jim Balter
    Jim Balter almost 10 years
    "it reveals intent" -- This is not a good justification. You could just write a comment in the code.
  • Martin Smith
    Martin Smith over 9 years
    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.
  • Jo So
    Jo So over 9 years
    @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)
  • Martin Smith
    Martin Smith over 9 years
    @JoSo - Nowhere does my comment dispute that.
  • ecoe
    ecoe over 9 years
    and yet the microsoft code example contradicts itself by checking if the directory exists first...
  • Paul Zahra
    Paul Zahra over 8 years
    As bazzilic said read up on CreateDirectory! "Creates all directories and subdirectories in the specified path unless they already exist." taken from msdn.microsoft.com/en-us/library/…
  • Giox
    Giox about 7 years
    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
  • Otávio Décio
    Otávio Décio about 7 years
    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).
  • Muflix
    Muflix about 7 years
    @OtávioDécio you mean file without an extension ?
  • Otávio Décio
    Otávio Décio about 7 years
    @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.
  • bergmeister
    bergmeister over 6 years
    CreateDirectory already handles the check if the directory does not exists.
  • bergmeister
    bergmeister over 6 years
    CreateDirectory already handles the check if the directory does not exists.
  • UJS
    UJS over 6 years
    @bergmeister ,Thanks .I just crossed checked .It really removed conditional check .Updated !!
  • Krythic
    Krythic about 6 years
    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.
  • VoteCoffee
    VoteCoffee about 6 years
    The one benefit of a check is that it creates an opportunity for meaningful logging. But certainly not needed for the basic mechanics.
  • soddoff Baldrick
    soddoff Baldrick over 4 years
    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
  • ComFreek
    ComFreek over 4 years
    This enables race conditions, see the accepted answer.
  • Tom Lint
    Tom Lint almost 4 years
    @soddoffBaldrick You must be doing something terribly wrong in your code, because neither Directory nor DirectoryInfo 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.
  • soddoff Baldrick
    soddoff Baldrick almost 4 years
    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.
  • Peter Mortensen
    Peter Mortensen over 3 years
    It could fail for other reasons, e.g. a virus checker kicking in at the worst possible time.
  • Peter Mortensen
    Peter Mortensen over 3 years
    How is this different from the answers from 2012?
  • Peter Mortensen
    Peter Mortensen over 3 years
    An explanation would be in order. It seems to do some more checks(?).
  • Peter Mortensen
    Peter Mortensen over 3 years
    But class FileUploadExtension is not used anywhere(?).
  • Peter Mortensen
    Peter Mortensen over 3 years
    What do you mean by "extend the FileUpload"?
  • MiguelSlv
    MiguelSlv over 3 years
    @PeterMortensen docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…. 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.
  • niico
    niico over 3 years
    @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).
  • jaiveeru
    jaiveeru about 3 years
    everyone talking about the same answer, but I liked the simplicity with which its explained here. Much easy and quick to understand. +1 from me
  • Naitik Singhal
    Naitik Singhal over 2 years
    Server is not defiened
  • bbsimonbb
    bbsimonbb over 2 years
    CreateDirectory() will happily create all the directories in a path. No need to put it in a loop.