DirectoryInfo.Create Метод

Определение

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

Перегрузки

Имя Описание
Create()

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

Create(DirectorySecurity)

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

Create()

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

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

Исключения

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

Примеры

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

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

Управление доступом, применяемое к каталогу.

Исключения

Вызывающий объект не имеет требуемого разрешения.

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

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

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

Примеры

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

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

Комментарии

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

Если каталог уже существует, этот метод ничего не делает.

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

Important

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

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