Si una carpeta no existe, créela


Uso un control FileUploader en mi aplicación. Quiero guardar un archivo en una carpeta especificada. Ahora quiero, si esta carpeta no existe, primero crearla y luego guardar mi archivo en esta carpeta. Si la carpeta ya existe, simplemente guarde el archivo en ella.

¿Cómo puedo hacer esto?

 523
Author: Jon Schneider, 2012-01-30

15 answers

Como otros han dicho, use System.IO.Directory.CreateDirectory

Pero, no es necesario comprobar si existe primero. De los documentos

Se crean todos y cada uno de los directorios especificados en path, a menos que ya existen o a menos que alguna parte de la ruta no sea válida. Camino parámetro especifica una ruta de directorio, no una ruta de archivo. Si el el directorio ya existe, este método no hace nada.

 931
Author: Mark Peters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-22 21:38:57

Utilice el siguiente código según http://forums.asp.net/p/1226236/2209871.aspx :

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));
 320
Author: Ravia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-04 19:01:50

Simplemente escribe esta línea:

System.IO.Directory.CreateDirectory(myDir);
  • Si la carpeta no no existe todavía, será creada.
  • Si la carpeta ya existe, la línea será ignorado.

Referencia: Artículo sobre el Directorio.CreateDirectory en MSDN

 184
Author: Nicolas Raoul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-13 03:39:15

Puede crear la ruta si aún no existe con un método como el siguiente:

using System.IO;

private void CreateIfMissing(string path)
{
  bool folderExists = Directory.Exists(Server.MapPath(path));
  if (!folderExists)
    Directory.CreateDirectory(Server.MapPath(path));
}
 29
Author: Dennis Traub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-30 14:53:14

Directory.Exists Esto explicará cómo comprobar si existe una ruta de archivo

Directory.CreateDirectory Esto explicará cómo intentar y crear la ruta de archivo si no existe

 27
Author: jeroenh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-15 14:38:29
using System.IO

if (!Directory.Exists(yourDirectory))
    Directory.CreateDirectory(yourDirectory);
 16
Author: BlackBear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-30 14:46:08

Puedes usar una cláusula try / catch y comprobar si existe:

  try
  {
    if (!Directory.Exists(path))
    {
       // Try to create the directory.
       DirectoryInfo di = Directory.CreateDirectory(path);
    }
  }
  catch (IOException ioex)
  {
     Console.WriteLine(ioex.Message);
  }
 16
Author: MethodMan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-26 14:01:02

Este método creará una carpeta si no existe y no hará nada si existe

Directory.CreateDirectory(path);
 13
Author: Thakur Rock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-30 14:07:34
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
 11
Author: KiranSolkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-15 10:16:35

El siguiente código es la mejor línea(s) de código que utilizo que creará el directorio si no está presente .

System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/temp/"));

Si el directorio ya existe, este método no crea un nuevo directorio, pero devuelve un objeto DirectoryInfo para el directorio existente. >

 5
Author: UJS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-13 12:54:56

Esta era la respuesta que estaba buscando, pero no fácilmente encontrar:

        string pathToNewFolder = System.IO.Path.Combine(parentFolderPath, "NewSubFolder");
        DirectoryInfo directory = Directory.CreateDirectory(pathToNewFolder); 
       // Will create if does not already exist (otherwise will ignore)
  • ruta a la nueva carpeta dada
  • variable de información de directorio para que pueda continuar manipulándolo como quiera.
 2
Author: BKSpurgeon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 11:02:19

Utilice el código siguiente. Utilicé este código para copiar archivos y crear una nueva carpeta.

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

   }
}
 1
Author: Lemon Kazi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-13 10:46:52

String createfolder = "E:/tmp /" + uId;
System. IO. Directory. CreateDirectory (createfolder);

 0
Author: amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-21 09:00:54
string root = @"C:\Temp";

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

// If directory does not exist, create it.

if (!Directory.Exists(root))
{

Directory.CreateDirectory(root);

}

El CreateDirectory también se usa para crear un subdirectorio. Todo lo que tiene que hacer es especificar la ruta del directorio en el que se creará este subdirectorio. El siguiente fragmento de código crea un subdirectorio Mahesh en C:\Temp directory.

// Create sub directory

if (!Directory.Exists(subdir))
{

Directory.CreateDirectory(subdir);

}
 -1
Author: uksp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-20 08:04:54

Derivado / combinado de múltiples respuestas, implementarlo para mí fue tan fácil como esto:

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

private void CreateDirectoryIfDoesNotExist(string dirName)
{
    System.IO.Directory.CreateDirectory(dirName);
}
 -2
Author: B. Clay Shannon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 18:40:25