If a folder does not exist, create it

C#asp.netDirectory

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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 - C#

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

Solution 6 - C#

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

Solution 7 - C#

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

Directory.CreateDirectory(path);

Solution 8 - C#

using System.IO

if (!Directory.Exists(yourDirectory))
    Directory.CreateDirectory(yourDirectory);

Solution 9 - C#

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

Solution 10 - C#

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

Solution 11 - C#

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.

Solution 12 - C#

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

Solution 13 - C#

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

Solution 14 - C#

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

Solution 15 - C#

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

}

Solution 16 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTavousiView Question on Stackoverflow
Solution 1 - C#Mark PetersView Answer on Stackoverflow
Solution 2 - C#Ravi VanapalliView Answer on Stackoverflow
Solution 3 - C#Nicolas RaoulView Answer on Stackoverflow
Solution 4 - C#jeroenhView Answer on Stackoverflow
Solution 5 - C#Dennis TraubView Answer on Stackoverflow
Solution 6 - C#MethodManView Answer on Stackoverflow
Solution 7 - C#Thakur RockView Answer on Stackoverflow
Solution 8 - C#BlackBearView Answer on Stackoverflow
Solution 9 - C#Kiran SolkarView Answer on Stackoverflow
Solution 10 - C#UJSView Answer on Stackoverflow
Solution 11 - C#BenKoshyView Answer on Stackoverflow
Solution 12 - C#JogiView Answer on Stackoverflow
Solution 13 - C#Lemon KaziView Answer on Stackoverflow
Solution 14 - C#MiguelSlvView Answer on Stackoverflow
Solution 15 - C#ukspView Answer on Stackoverflow
Solution 16 - C#B. Clay Shannon-B. Crow RavenView Answer on Stackoverflow