web-dev-qa-db-fra.com

Vérifier si un dossier existe dans un répertoire et les créer en utilisant C #

Comment puis-je vérifier si le répertoire C:/ contient un dossier nommé MP_Upload, et s'il n'existe pas, créer le dossier automatiquement?

J'utilise Visual Studio 2005 C #.

92
gymcode

Cela devrait aider:

using System.IO;
...

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

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

Directory.CreateDirectory fait exactement ce que vous voulez: Il crée le répertoire s’il n’existe pas encore. Il n'est pas nécessaire de faire une vérification explicite au préalable.

Tous les répertoires spécifiés dans path sont créés, sauf s’ils existent déjà ou si une partie du chemin n’est pas valide. Le paramètre path spécifie un chemin de répertoire, pas un chemin de fichier. Si le répertoire existe déjà, cette méthode ne fait rien.

(Cela signifie également que tous les répertoires le long du chemin sont créés si nécessaire: CreateDirectory(@"C:\a\b\c\d") suffit, même si C:\a n'existe pas encore.)


Permettez-moi d’ajouter un mot d’avertissement concernant votre choix de répertoire: La création d’un dossier directement sous la racine de la partition système C:\ est mal vue. Pensez à laisser l'utilisateur choisir un dossier ou créer un dossier dans %APPDATA% ou %LOCALAPPDATA% à la place (utilisez Environment.GetFolderPath pour cela). La page MSDN de l'énumération Environment.SpecialFolder contient une liste des dossiers du système d'exploitation spéciaux et de leurs fonctions.

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

Cela devrait marcher

if(!Directory.Exists(@"C:\MP_Upload")) {
    Directory.CreateDirectory(@"C:\MP_Upload");
}
6
kufi
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;
            }
        }
    }
}
2
Azam Rahimjonov
    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
1
Ronaldo Albertini

Vous pouvez essayer ça ..

using System.IO;string path = "C:\MP_Upload";if(!Directory.Exists(path)){
   Directory.CreateDirectory(path);}
0
Ashish