DirectoryInfo(String) Конструктор

Определение

Выполняет инициализацию нового экземпляра класса DirectoryInfo для заданного пути.

public:
 DirectoryInfo(System::String ^ path);
public DirectoryInfo (string path);
new System.IO.DirectoryInfo : string -> System.IO.DirectoryInfo
Public Sub New (path As String)

Параметры

path
String

Строка, содержащая путь, для которого создается класс DirectoryInfo.

Исключения

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

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

платформа .NET Framework и .NET Core версий старше 2.1: path содержит недопустимые символы, такие как ", <, >или |.

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

Примеры

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

using namespace System;
using namespace System::IO;
int main()
{
   
   // Specify the directories you want to manipulate.
   DirectoryInfo^ di1 = gcnew DirectoryInfo( "c:\\MyDir" );
   DirectoryInfo^ di2 = gcnew DirectoryInfo( "c:\\MyDir\\temp" );
   try
   {
      
      // Create the directories.
      di1->Create();
      di2->Create();
      
      // This operation will not be allowed because there are subdirectories.
      Console::WriteLine( "I am about to attempt to delete {0}.", di1->Name );
      di1->Delete();
      Console::WriteLine( "The Delete operation was successful, which was unexpected." );
   }
   catch ( Exception^ ) 
   {
      Console::WriteLine( "The Delete operation failed as expected." );
   }

}
using System;
using System.IO;

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

        try
        {
            // Create the directories.
            di1.Create();
            di2.Create();

            // This operation will not be allowed because there are subdirectories.
            Console.WriteLine("I am about to attempt to delete {0}.", di1.Name);
            di1.Delete();
            Console.WriteLine("The Delete operation was successful, which was unexpected.");
        }
        catch (Exception)
        {
            Console.WriteLine("The Delete operation failed as expected.");
        }
        finally {}
    }
}
open System.IO

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

try
    // Create the directories.
    di1.Create()
    di2.Create()

    // This operation will not be allowed because there are subdirectories.
    printfn $"I am about to attempt to delete {di1.Name}."
    di1.Delete()
    printfn "The Delete operation was successful, which was unexpected."
with _ ->
    printfn "The Delete operation failed as expected."
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di1 As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Dim di2 As DirectoryInfo = New DirectoryInfo("c:\MyDir\temp")
        Try
            ' Create the directories.
            di1.Create()
            di2.Create()
            ' This operation will not be allowed because there are subdirectories.
            Console.WriteLine("I am about to attempt to delete {0}.", di1.Name)
            di1.Delete()
            Console.WriteLine("The Delete operation was successful, which was unexpected.")
        Catch e As Exception
            Console.WriteLine("The Delete operation failed as expected.")
        End Try
    End Sub
End Class

Комментарии

Этот конструктор не проверяет, существует ли каталог. Этот конструктор является заполнителем для строки, которая используется для доступа к диску в последующих операциях.

Параметр path может быть именем файла, включая файл в UNC-ресурсе.

Внимание!

Если вы компилируете набор символов с определенными культурными параметрами и извлекаете те же самые символы с другим параметром и региональных параметров, символы могут быть не интерпретируемыми, что может привести к возникновению исключения.

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

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

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