[c#] Check if a folder exist in a directory and create them using C#

How can I check if directory C:/ contains a folder named MP_Upload, and if it does not exist, create the folder automatically?

I am using Visual Studio 2005 C#.

This question is related to c# asp.net visual-studio

The answer is


This should help:

using System.IO;
...

string path = @"C:\MP_Upload";
if(!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

using System;
using System.IO;
using System.Windows.Forms;

namespace DirCombination 
{
    public partial class DirCombination : Form
    {
        private const string _Path = @"D:/folder1/foler2/folfer3/folder4/file.txt";
        private string _finalPath = null;
        private string _error = null;

        public DirCombination()
        {
            InitializeComponent();

            if (!FSParse(_Path))
                Console.WriteLine(_error);
            else
                Console.WriteLine(_finalPath);
        }

        private bool FSParse(string path)
        {
            try
            {
                string[] Splited = path.Replace(@"//", @"/").Replace(@"\\", @"/").Replace(@"\", "/").Split(':');
                string NewPath = Splited[0] + ":";
                if (Directory.Exists(NewPath))
                {                    
                    string[] Paths = Splited[1].Substring(1).Split('/');

                    for (int i = 0; i < Paths.Length - 1; i++)
                    {
                        NewPath += "/";
                        if (!string.IsNullOrEmpty(Paths[i]))
                        {
                            NewPath += Paths[i];
                            if (!Directory.Exists(NewPath))
                                Directory.CreateDirectory(NewPath);
                        }
                    }

                    if (!string.IsNullOrEmpty(Paths[Paths.Length - 1]))
                    {
                        NewPath += "/" + Paths[Paths.Length - 1];
                        if (!File.Exists(NewPath))
                            File.Create(NewPath);
                    }
                    _finalPath = NewPath;
                    return true;
                }
                else
                {
                    _error = "Drive is not exists!";
                    return false;
                }
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return false;
            }
        }
    }
}

using System.IO;
...

Directory.CreateDirectory(@"C:\MP_Upload");

Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.

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.

(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d") suffices, even if C:\a does not exist yet.)


Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\ is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA% or %LOCALAPPDATA% instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.


    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

This should work

if(!Directory.Exists(@"C:\MP_Upload")) {
    Directory.CreateDirectory(@"C:\MP_Upload");
}

if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
     System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references