DirectoryInfo.Create Метод

Определение

Создает каталог.

Перегрузки

Create()

Создает каталог.

Create(DirectorySecurity)

Создает каталог с помощью объекта DirectorySecurity.

Create()

Исходный код:
DirectoryInfo.cs
Исходный код:
DirectoryInfo.cs
Исходный код:
DirectoryInfo.cs

Создает каталог.

public:
 void Create();
public void Create ();
member this.Create : unit -> unit
Public Sub Create ()

Исключения

Не удалось создать каталог.

Примеры

В следующем примере проверяется, существует ли указанный каталог, создается каталог, если он не существует, и удаляется каталог.

using namespace System;
using namespace System::IO;
int main()
{
   
   // Specify the directories you want to manipulate.
   DirectoryInfo^ di = gcnew DirectoryInfo( "c:\\MyDir" );
   try
   {
      
      // Determine whether the directory exists.
      if ( di->Exists )
      {
         
         // Indicate that it already exists.
         Console::WriteLine( "That path exists already." );
         return 0;
      }
      
      // Try to create the directory.
      di->Create();
      Console::WriteLine( "The directory was created successfully." );
      
      // Delete the directory.
      di->Delete();
      Console::WriteLine( "The directory was deleted successfully." );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }

}
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        // Specify the directories you want to manipulate.
        DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");

        try
        {
            // Determine whether the directory exists.
            if (di.Exists)
            {
                // Indicate that it already exists.
                Console.WriteLine("That path exists already.");
                return;
            }

            // Try to create the directory.
            di.Create();
            Console.WriteLine("The directory was created successfully.");

            // Delete the directory.
            di.Delete();
            Console.WriteLine("The directory was deleted successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
        finally {}
    }
}
open System.IO

// Specify the directories you want to manipulate.
let di = DirectoryInfo @"c:\MyDir"

try
    // Determine whether the directory exists.
    if di.Exists then
        // Indicate that it already exists.
        printfn "That path exists already."
    else
        // Try to create the directory.
        di.Create()
        printfn "The directory was created successfully."

        // Delete the directory.
        di.Delete()
        printfn "The directory was deleted successfully."
with e ->
    printfn $"The process failed: {e}"
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            'Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Комментарии

Создаются все каталоги и все каталоги, указанные в , path если только часть не является недопустимой path . Параметр path указывает путь к каталогу, а не путь к файлу. Если каталог уже существует, этот метод не выполняет никаких действий. Если каталог не существовал до вызова этого метода, все кэшированные сведения об атрибутах каталога будут удалены в случае успешного создания.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Create(DirectorySecurity)

Создает каталог с помощью объекта DirectorySecurity.

public:
 void Create(System::Security::AccessControl::DirectorySecurity ^ directorySecurity);
public void Create (System.Security.AccessControl.DirectorySecurity directorySecurity);
member this.Create : System.Security.AccessControl.DirectorySecurity -> unit
Public Sub Create (directorySecurity As DirectorySecurity)

Параметры

directorySecurity
DirectorySecurity

Элемент управления доступом, который необходимо применить к каталогу.

Исключения

У вызывающего объекта отсутствует необходимое разрешение.

платформа .NET Framework и .NET Core версий старше 2.1: path строка нулевой длины, содержит только пробелы или содержит один или несколько недопустимых символов. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars().

path имеет значение null.

Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе.

Указан недопустимый путь (например, он ведет на несопоставленный диск).

Предпринята попытка создать каталог с единственным знаком двоеточия (:).

Примеры

В следующем примере кода создается новый каталог во временной папке пользователя с указанными атрибутами безопасности каталога:

using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace ConsoleApp
{
    class Program
    {
        static void Main()
        {
            DirectorySecurity security = new DirectorySecurity();
            SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            FileSystemAccessRule accessRule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow);
            security.AddAccessRule(accessRule);
            string path = Path.Combine(Path.GetTempPath(), "directoryToCreate");
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            dirInfo.Create(security);
        }
    }
}

Комментарии

Используйте эту перегрузку метода для создания каталога с контролем доступа, поэтому вероятность того, что доступ к каталогу не будет осуществляться до применения безопасности, нет.

Если каталог уже существует, этот метод не выполняет никаких действий.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

Важно!

Этот метод был перенесен в .NET Core 3.1 в качестве метода FileSystemAclExtensions расширения класса в составе сборки System.Security.AccessControl : Create(DirectoryInfo, DirectorySecurity).

Применяется к