Directory.GetFileSystemEntries Метод

Определение

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

Перегрузки

GetFileSystemEntries(String)

Возвращает имена всех файлов и подкаталогов по указанному пути.

GetFileSystemEntries(String, String)

Возвращает массив имен файлов и имен каталогов по указанному пути, соответствующих шаблону поиска.

GetFileSystemEntries(String, String, EnumerationOptions)

Возвращает массив имен файлов и имен каталогов по указанному пути, соответствующих шаблону поиска и параметрам перечисления.

GetFileSystemEntries(String, String, SearchOption)

Возвращает массив всех имен файлов и каталогов по указанному пути, соответствующих шаблону поиска, и при необходимости ведет поиск в подкаталогах.

GetFileSystemEntries(String)

Возвращает имена всех файлов и подкаталогов по указанному пути.

public:
 static cli::array <System::String ^> ^ GetFileSystemEntries(System::String ^ path);
public static string[] GetFileSystemEntries (string path);
static member GetFileSystemEntries : string -> string[]
Public Shared Function GetFileSystemEntries (path As String) As String()

Параметры

path
String

Относительный или абсолютный путь к каталогу для поиска. В этой строке не учитывается регистр знаков.

Возвращаемое значение

String[]

Массив имен файлов и подкаталогов в указанном каталоге или пустой массив, если файлы или подкаталоги не найдены.

Исключения

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

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

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

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

path — это имя файла.

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

Примеры

В следующем примере метод используется GetFileSystemEntries для заполнения массива строк именами всех файлов и подкаталогов в указанном пользователем расположении и выводит каждую строку в массиве в консоль. Этот пример настроен для перехвата всех ошибок, общих для этого метода.

using namespace System;
class Class1
{
public:
   void PrintFileSystemEntries( String^ path )
   {
      try
      {
         
         // Obtain the file system entries in the directory path.
         array<String^>^directoryEntries = System::IO::Directory::GetFileSystemEntries( path );
         for ( int i = 0; i < directoryEntries->Length; i++ )
         {
            System::Console::WriteLine( directoryEntries[ i ] );

         }
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, \HelloServer'                  or contains invalid characters." );
      }
      catch ( System::IO::DirectoryNotFoundException^ ) 
      {
         System::Console::WriteLine(  "The path encapsulated in the \HelloServer'                  Directory object does not exist." );
      }

   }

   void PrintFileSystemEntries( String^ path, String^ pattern )
   {
      try
      {
         
         // Obtain the file system entries in the directory
         // path that match the pattern.
         array<String^>^directoryEntries = System::IO::Directory::GetFileSystemEntries( path, pattern );
         for ( int i = 0; i < directoryEntries->Length; i++ )
         {
            System::Console::WriteLine( directoryEntries[ i ] );

         }
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, \HelloServer'                  or contains invalid characters." );
      }
      catch ( System::IO::DirectoryNotFoundException^ ) 
      {
         System::Console::WriteLine(  "The path encapsulated in the \HelloServer'                  Directory object does not exist." );
      }

   }


   // Print out all logical drives on the system.
   void GetLogicalDrives()
   {
      try
      {
         array<String^>^drives = System::IO::Directory::GetLogicalDrives();
         for ( int i = 0; i < drives->Length; i++ )
         {
            System::Console::WriteLine( drives[ i ] );

         }
      }
      catch ( System::IO::IOException^ ) 
      {
         System::Console::WriteLine(  "An I/O error occurs." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }

   }

   void GetParent( String^ path )
   {
      try
      {
         System::IO::DirectoryInfo^ directoryInfo = System::IO::Directory::GetParent( path );
         System::Console::WriteLine( directoryInfo->FullName );
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, or \HelloServer'                  contains invalid characters." );
      }

   }

   void Move( String^ sourcePath, String^ destinationPath )
   {
      try
      {
         System::IO::Directory::Move( sourcePath, destinationPath );
         System::Console::WriteLine(  "The directory move is complete." );
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, \HelloServer'                  or contains invalid characters." );
      }
      catch ( System::IO::IOException^ ) 
      {
         System::Console::WriteLine(  "An attempt was made to move a \HelloServer'                  directory to a different \HelloServer'                  volume, or destDirName \HelloServer'                  already exists." );
      }

   }

};

int main()
{
   Class1 * snippets = new Class1;
   String^ path = System::IO::Directory::GetCurrentDirectory();
   String^ filter =  "*.exe";
   snippets->PrintFileSystemEntries( path );
   snippets->PrintFileSystemEntries( path, filter );
   snippets->GetLogicalDrives();
   snippets->GetParent( path );
   snippets->Move(  "C:\\proof",  "C:\\Temp" );
   return 0;
}
using System;

namespace GetFileSystemEntries
{
    class Class1
    {
        static void Main(string[] args)
        {
            Class1 snippets = new Class1();

            string path = System.IO.Directory.GetCurrentDirectory();
            string filter = "*.exe";

            snippets.PrintFileSystemEntries(path);
            snippets.PrintFileSystemEntries(path, filter);		
            snippets.GetLogicalDrives();
            snippets.GetParent(path);
            snippets.Move("C:\\proof", "C:\\Temp");
        }

        void PrintFileSystemEntries(string path)
        {
            
            try
            {
                // Obtain the file system entries in the directory path.
                string[] directoryEntries =
                    System.IO.Directory.GetFileSystemEntries(path);

                foreach (string str in directoryEntries)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                System.Console.WriteLine("The path encapsulated in the " +
                    "Directory object does not exist.");
            }
        }
        void PrintFileSystemEntries(string path, string pattern)
        {
            try
            {
                // Obtain the file system entries in the directory
                // path that match the pattern.
                string[] directoryEntries =
                    System.IO.Directory.GetFileSystemEntries(path, pattern);

                foreach (string str in directoryEntries)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                System.Console.WriteLine("The path encapsulated in the " +
                    "Directory object does not exist.");
            }
        }

        // Print out all logical drives on the system.
        void GetLogicalDrives()
        {
            try
            {
                string[] drives = System.IO.Directory.GetLogicalDrives();

                foreach (string str in drives)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (System.IO.IOException)
            {
                System.Console.WriteLine("An I/O error occurs.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
        }
        void GetParent(string path)
        {
            try
            {
                System.IO.DirectoryInfo directoryInfo =
                    System.IO.Directory.GetParent(path);

                System.Console.WriteLine(directoryInfo.FullName);
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, or " +
                    "contains invalid characters.");
            }
        }
        void Move(string sourcePath, string destinationPath)
        {
            try
            {
                System.IO.Directory.Move(sourcePath, destinationPath);
                System.Console.WriteLine("The directory move is complete.");
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");	
            }
            catch (System.IO.IOException)
            {
                System.Console.WriteLine("An attempt was made to move a " +
                    "directory to a different " +
                    "volume, or destDirName " +
                    "already exists.");
            }
        }
    }
}
open System
open System.IO
open System.Security

let printFileSystemEntries path =
    try
        // Obtain the file system entries in the directory path.
        let directoryEntries = Directory.GetFileSystemEntries path

        for str in directoryEntries do
            printfn $"{str}"
    with 
    | :? ArgumentNullException ->
        printfn "Path is a null reference."
    | :? SecurityException ->
        printfn $"The caller does not have the required permission."
    | :? ArgumentException ->
        printfn $"Path is an empty string, contains only white spaces, or contains invalid characters."
    | :? DirectoryNotFoundException ->
        printfn $"The path encapsulated in the Directory object does not exist."

let printFileSystemEntriesPattern path pattern =
    try
        // Obtain the file system entries in the directory
        // path that match the pattern.
        let directoryEntries = Directory.GetFileSystemEntries(path, pattern)

        for str in directoryEntries do
            printfn $"{str}"
    with
    | :? ArgumentNullException -> printfn "Path is a null reference."
    | :? SecurityException -> printfn "The caller does not have the required permission."
    | :? ArgumentException -> printfn "Path is an empty string, contains only white spaces, or contains invalid characters."
    | :? DirectoryNotFoundException -> printfn "The path encapsulated in the Directory object does not exist."

// Print out all logical drives on the system.
let getLogicalDrives () =
    try
        let drives = Directory.GetLogicalDrives()

        for str in drives do
            printfn $"{str}"
    with
    | :? IOException -> printfn "An I/O error occurs."
    | :? SecurityException -> printfn "The caller does not have the required permission."

let getParent path =
    try
        let directoryInfo = Directory.GetParent path
        printfn $"{directoryInfo.FullName}"

    with
    | :? ArgumentNullException -> printfn "Path is a null reference."
    | :? ArgumentException -> printfn "Path is an empty string, contains only white spaces, or contains invalid characters."

let move sourcePath destinationPath =
    try
        Directory.Move(sourcePath, destinationPath)
        printfn "The directory move is complete."

    with
    | :? ArgumentNullException -> printfn "Path is a null reference."
    | :? SecurityException -> printfn "The caller does not have the required permission."
    | :? ArgumentException -> printfn "Path is an empty string, contains only white spaces, or contains invalid characters."
    | :? IOException -> printfn "An attempt was made to move a directory to a different volume, or destDirName already exists."

let path = Directory.GetCurrentDirectory()
let filter = "*.exe"

printFileSystemEntries path
printFileSystemEntriesPattern path filter
getLogicalDrives ()
getParent path
move "C:\\proof" "C:\\Temp"
Option Explicit On 
Option Strict On

Namespace GetFileSystemEntries
    Class Class1
        Overloads Shared Sub Main(ByVal args() As String)
            Dim snippets As New Class1()
            Dim path As String = System.IO.Directory.GetCurrentDirectory()
            Dim filter As String = "*.exe"
            snippets.PrintFileSystemEntries(path)
            snippets.PrintFileSystemEntries(path, filter)
            snippets.GetLogicalDrives()
            snippets.GetParent(path)
            snippets.Move("C:\proof", "C:\Temp")
        End Sub

        Sub PrintFileSystemEntries(ByVal path As String)
            Try
                ' Obtain the file system entries in the directory path.
                Dim directoryEntries As String()
                directoryEntries = System.IO.Directory.GetFileSystemEntries(path)
                Dim str As String
                For Each str In directoryEntries
                    System.Console.WriteLine(str)
                Next str
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                        "required permission.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                        "contains only white spaces, " + _
                                        "or contains invalid characters.")
            Catch exp As System.IO.DirectoryNotFoundException
                System.Console.WriteLine("The path encapsulated in the " + _
                                        "Directory object does not exist.")
            End Try
        End Sub
        Sub PrintFileSystemEntries(ByVal path As String, _
                                   ByVal pattern As String)
            Try
                ' Obtain the file system entries in the directory
                ' path that match the pattern.
                Dim directoryEntries As String()
                directoryEntries = _
                   System.IO.Directory.GetFileSystemEntries(path, pattern)

                Dim str As String
                For Each str In directoryEntries
                    System.Console.WriteLine(str)
                Next str
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                        "required permission.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                        "contains only white spaces, " + _
                                        "or contains invalid characters.")
            Catch exp As System.IO.DirectoryNotFoundException
                System.Console.WriteLine("The path encapsulated in the " + _
                                        "Directory object does not exist.")
            End Try
        End Sub

        ' Print out all logical drives on the system.
        Sub GetLogicalDrives()
            Try
                Dim drives As String()
                drives = System.IO.Directory.GetLogicalDrives()

                Dim str As String
                For Each str In drives
                    System.Console.WriteLine(str)
                Next str
            Catch exp As System.IO.IOException
                System.Console.WriteLine("An I/O error occurs.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                           "required permission.")
            End Try
        End Sub
        Sub GetParent(ByVal path As String)
            Try
                Dim directoryInfo As System.IO.DirectoryInfo
                directoryInfo = System.IO.Directory.GetParent(path)
                System.Console.WriteLine(directoryInfo.FullName)
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                     "contains only white spaces, or " + _
                                     "contains invalid characters.")
            End Try
        End Sub
        Sub Move(ByVal sourcePath As String, ByVal destinationPath As String)
            Try
                System.IO.Directory.Move(sourcePath, destinationPath)
                System.Console.WriteLine("The directory move is complete.")
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                           "required permission.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                        "contains only white spaces, " + _
                                        "or contains invalid characters.")
            Catch exp As System.IO.IOException
                System.Console.WriteLine("An attempt was made to move a " + _
                                        "directory to a different " + _
                                        "volume, or destDirName " + _
                                        "already exists.")
            End Try
        End Sub
    End Class
End Namespace

Комментарии

Порядок возвращаемых имен файлов и каталогов не гарантируется; используйте метод , Sort если требуется определенный порядок сортировки.

Методы EnumerateFileSystemEntries и GetFileSystemEntries отличаются следующим образом: при использовании EnumerateFileSystemEntriesможно начать перечисление коллекции записей до возврата всей коллекции. При использовании GetFileSystemEntriesнеобходимо дождаться возврата всего массива записей, прежде чем получить доступ к массиву. Таким образом, при работе с большим количеством файлов и каталогов EnumerateFileSystemEntries может быть более эффективным.

Этот метод идентичен GetFileSystemEntries звездочку (*), указанную в качестве шаблона поиска.

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

Чувствительность параметра к регистру path соответствует значению файловой системы, в которой выполняется код. Например, регистр не учитывается в NTFS (файловая система Windows по умолчанию) и учитывает регистр в файловых системах Linux.

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

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

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

GetFileSystemEntries(String, String)

Возвращает массив имен файлов и имен каталогов по указанному пути, соответствующих шаблону поиска.

public:
 static cli::array <System::String ^> ^ GetFileSystemEntries(System::String ^ path, System::String ^ searchPattern);
public static string[] GetFileSystemEntries (string path, string searchPattern);
static member GetFileSystemEntries : string * string -> string[]
Public Shared Function GetFileSystemEntries (path As String, searchPattern As String) As String()

Параметры

path
String

Относительный или абсолютный путь к каталогу для поиска. В этой строке не учитывается регистр знаков.

searchPattern
String

Строка поиска, которая будет сравниваться с именами файла и каталогов в path. Этот параметр может содержать сочетание допустимого литерального пути и подстановочного символа (* и ?), но не поддерживает регулярные выражения.

Возвращаемое значение

String[]

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

Исключения

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

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

-или-

searchPattern не содержит допустимый шаблон.

Параметр path или searchPattern имеет значение null.

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

path — это имя файла.

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

Примеры

В следующем примере метод используется GetFileSystemEntries для заполнения массива строк именами всех файлов, соответствующих пользовательскому фильтру в определенном расположении, и выводит каждую строку в массиве в консоль. Этот пример настроен для перехвата всех ошибок, общих для этого метода.

using namespace System;
class Class1
{
public:
   void PrintFileSystemEntries( String^ path )
   {
      try
      {
         
         // Obtain the file system entries in the directory path.
         array<String^>^directoryEntries = System::IO::Directory::GetFileSystemEntries( path );
         for ( int i = 0; i < directoryEntries->Length; i++ )
         {
            System::Console::WriteLine( directoryEntries[ i ] );

         }
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, \HelloServer'                  or contains invalid characters." );
      }
      catch ( System::IO::DirectoryNotFoundException^ ) 
      {
         System::Console::WriteLine(  "The path encapsulated in the \HelloServer'                  Directory object does not exist." );
      }

   }

   void PrintFileSystemEntries( String^ path, String^ pattern )
   {
      try
      {
         
         // Obtain the file system entries in the directory
         // path that match the pattern.
         array<String^>^directoryEntries = System::IO::Directory::GetFileSystemEntries( path, pattern );
         for ( int i = 0; i < directoryEntries->Length; i++ )
         {
            System::Console::WriteLine( directoryEntries[ i ] );

         }
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, \HelloServer'                  or contains invalid characters." );
      }
      catch ( System::IO::DirectoryNotFoundException^ ) 
      {
         System::Console::WriteLine(  "The path encapsulated in the \HelloServer'                  Directory object does not exist." );
      }

   }


   // Print out all logical drives on the system.
   void GetLogicalDrives()
   {
      try
      {
         array<String^>^drives = System::IO::Directory::GetLogicalDrives();
         for ( int i = 0; i < drives->Length; i++ )
         {
            System::Console::WriteLine( drives[ i ] );

         }
      }
      catch ( System::IO::IOException^ ) 
      {
         System::Console::WriteLine(  "An I/O error occurs." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }

   }

   void GetParent( String^ path )
   {
      try
      {
         System::IO::DirectoryInfo^ directoryInfo = System::IO::Directory::GetParent( path );
         System::Console::WriteLine( directoryInfo->FullName );
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, or \HelloServer'                  contains invalid characters." );
      }

   }

   void Move( String^ sourcePath, String^ destinationPath )
   {
      try
      {
         System::IO::Directory::Move( sourcePath, destinationPath );
         System::Console::WriteLine(  "The directory move is complete." );
      }
      catch ( ArgumentNullException^ ) 
      {
         System::Console::WriteLine(  "Path is a null reference." );
      }
      catch ( System::Security::SecurityException^ ) 
      {
         System::Console::WriteLine(  "The caller does not have the \HelloServer'                  required permission." );
      }
      catch ( ArgumentException^ ) 
      {
         System::Console::WriteLine(  "Path is an empty String, \HelloServer'                  contains only white spaces, \HelloServer'                  or contains invalid characters." );
      }
      catch ( System::IO::IOException^ ) 
      {
         System::Console::WriteLine(  "An attempt was made to move a \HelloServer'                  directory to a different \HelloServer'                  volume, or destDirName \HelloServer'                  already exists." );
      }

   }

};

int main()
{
   Class1 * snippets = new Class1;
   String^ path = System::IO::Directory::GetCurrentDirectory();
   String^ filter =  "*.exe";
   snippets->PrintFileSystemEntries( path );
   snippets->PrintFileSystemEntries( path, filter );
   snippets->GetLogicalDrives();
   snippets->GetParent( path );
   snippets->Move(  "C:\\proof",  "C:\\Temp" );
   return 0;
}
using System;

namespace GetFileSystemEntries
{
    class Class1
    {
        static void Main(string[] args)
        {
            Class1 snippets = new Class1();

            string path = System.IO.Directory.GetCurrentDirectory();
            string filter = "*.exe";

            snippets.PrintFileSystemEntries(path);
            snippets.PrintFileSystemEntries(path, filter);		
            snippets.GetLogicalDrives();
            snippets.GetParent(path);
            snippets.Move("C:\\proof", "C:\\Temp");
        }

        void PrintFileSystemEntries(string path)
        {
            
            try
            {
                // Obtain the file system entries in the directory path.
                string[] directoryEntries =
                    System.IO.Directory.GetFileSystemEntries(path);

                foreach (string str in directoryEntries)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                System.Console.WriteLine("The path encapsulated in the " +
                    "Directory object does not exist.");
            }
        }
        void PrintFileSystemEntries(string path, string pattern)
        {
            try
            {
                // Obtain the file system entries in the directory
                // path that match the pattern.
                string[] directoryEntries =
                    System.IO.Directory.GetFileSystemEntries(path, pattern);

                foreach (string str in directoryEntries)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                System.Console.WriteLine("The path encapsulated in the " +
                    "Directory object does not exist.");
            }
        }

        // Print out all logical drives on the system.
        void GetLogicalDrives()
        {
            try
            {
                string[] drives = System.IO.Directory.GetLogicalDrives();

                foreach (string str in drives)
                {
                    System.Console.WriteLine(str);
                }
            }
            catch (System.IO.IOException)
            {
                System.Console.WriteLine("An I/O error occurs.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
        }
        void GetParent(string path)
        {
            try
            {
                System.IO.DirectoryInfo directoryInfo =
                    System.IO.Directory.GetParent(path);

                System.Console.WriteLine(directoryInfo.FullName);
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, or " +
                    "contains invalid characters.");
            }
        }
        void Move(string sourcePath, string destinationPath)
        {
            try
            {
                System.IO.Directory.Move(sourcePath, destinationPath);
                System.Console.WriteLine("The directory move is complete.");
            }
            catch (ArgumentNullException)
            {
                System.Console.WriteLine("Path is a null reference.");
            }
            catch (System.Security.SecurityException)
            {
                System.Console.WriteLine("The caller does not have the " +
                    "required permission.");
            }
            catch (ArgumentException)
            {
                System.Console.WriteLine("Path is an empty string, " +
                    "contains only white spaces, " +
                    "or contains invalid characters.");	
            }
            catch (System.IO.IOException)
            {
                System.Console.WriteLine("An attempt was made to move a " +
                    "directory to a different " +
                    "volume, or destDirName " +
                    "already exists.");
            }
        }
    }
}
open System
open System.IO
open System.Security

let printFileSystemEntries path =
    try
        // Obtain the file system entries in the directory path.
        let directoryEntries = Directory.GetFileSystemEntries path

        for str in directoryEntries do
            printfn $"{str}"
    with 
    | :? ArgumentNullException ->
        printfn "Path is a null reference."
    | :? SecurityException ->
        printfn $"The caller does not have the required permission."
    | :? ArgumentException ->
        printfn $"Path is an empty string, contains only white spaces, or contains invalid characters."
    | :? DirectoryNotFoundException ->
        printfn $"The path encapsulated in the Directory object does not exist."

let printFileSystemEntriesPattern path pattern =
    try
        // Obtain the file system entries in the directory
        // path that match the pattern.
        let directoryEntries = Directory.GetFileSystemEntries(path, pattern)

        for str in directoryEntries do
            printfn $"{str}"
    with
    | :? ArgumentNullException -> printfn "Path is a null reference."
    | :? SecurityException -> printfn "The caller does not have the required permission."
    | :? ArgumentException -> printfn "Path is an empty string, contains only white spaces, or contains invalid characters."
    | :? DirectoryNotFoundException -> printfn "The path encapsulated in the Directory object does not exist."

// Print out all logical drives on the system.
let getLogicalDrives () =
    try
        let drives = Directory.GetLogicalDrives()

        for str in drives do
            printfn $"{str}"
    with
    | :? IOException -> printfn "An I/O error occurs."
    | :? SecurityException -> printfn "The caller does not have the required permission."

let getParent path =
    try
        let directoryInfo = Directory.GetParent path
        printfn $"{directoryInfo.FullName}"

    with
    | :? ArgumentNullException -> printfn "Path is a null reference."
    | :? ArgumentException -> printfn "Path is an empty string, contains only white spaces, or contains invalid characters."

let move sourcePath destinationPath =
    try
        Directory.Move(sourcePath, destinationPath)
        printfn "The directory move is complete."

    with
    | :? ArgumentNullException -> printfn "Path is a null reference."
    | :? SecurityException -> printfn "The caller does not have the required permission."
    | :? ArgumentException -> printfn "Path is an empty string, contains only white spaces, or contains invalid characters."
    | :? IOException -> printfn "An attempt was made to move a directory to a different volume, or destDirName already exists."

let path = Directory.GetCurrentDirectory()
let filter = "*.exe"

printFileSystemEntries path
printFileSystemEntriesPattern path filter
getLogicalDrives ()
getParent path
move "C:\\proof" "C:\\Temp"
Option Explicit On 
Option Strict On

Namespace GetFileSystemEntries
    Class Class1
        Overloads Shared Sub Main(ByVal args() As String)
            Dim snippets As New Class1()
            Dim path As String = System.IO.Directory.GetCurrentDirectory()
            Dim filter As String = "*.exe"
            snippets.PrintFileSystemEntries(path)
            snippets.PrintFileSystemEntries(path, filter)
            snippets.GetLogicalDrives()
            snippets.GetParent(path)
            snippets.Move("C:\proof", "C:\Temp")
        End Sub

        Sub PrintFileSystemEntries(ByVal path As String)
            Try
                ' Obtain the file system entries in the directory path.
                Dim directoryEntries As String()
                directoryEntries = System.IO.Directory.GetFileSystemEntries(path)
                Dim str As String
                For Each str In directoryEntries
                    System.Console.WriteLine(str)
                Next str
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                        "required permission.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                        "contains only white spaces, " + _
                                        "or contains invalid characters.")
            Catch exp As System.IO.DirectoryNotFoundException
                System.Console.WriteLine("The path encapsulated in the " + _
                                        "Directory object does not exist.")
            End Try
        End Sub
        Sub PrintFileSystemEntries(ByVal path As String, _
                                   ByVal pattern As String)
            Try
                ' Obtain the file system entries in the directory
                ' path that match the pattern.
                Dim directoryEntries As String()
                directoryEntries = _
                   System.IO.Directory.GetFileSystemEntries(path, pattern)

                Dim str As String
                For Each str In directoryEntries
                    System.Console.WriteLine(str)
                Next str
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                        "required permission.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                        "contains only white spaces, " + _
                                        "or contains invalid characters.")
            Catch exp As System.IO.DirectoryNotFoundException
                System.Console.WriteLine("The path encapsulated in the " + _
                                        "Directory object does not exist.")
            End Try
        End Sub

        ' Print out all logical drives on the system.
        Sub GetLogicalDrives()
            Try
                Dim drives As String()
                drives = System.IO.Directory.GetLogicalDrives()

                Dim str As String
                For Each str In drives
                    System.Console.WriteLine(str)
                Next str
            Catch exp As System.IO.IOException
                System.Console.WriteLine("An I/O error occurs.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                           "required permission.")
            End Try
        End Sub
        Sub GetParent(ByVal path As String)
            Try
                Dim directoryInfo As System.IO.DirectoryInfo
                directoryInfo = System.IO.Directory.GetParent(path)
                System.Console.WriteLine(directoryInfo.FullName)
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                     "contains only white spaces, or " + _
                                     "contains invalid characters.")
            End Try
        End Sub
        Sub Move(ByVal sourcePath As String, ByVal destinationPath As String)
            Try
                System.IO.Directory.Move(sourcePath, destinationPath)
                System.Console.WriteLine("The directory move is complete.")
            Catch exp As ArgumentNullException
                System.Console.WriteLine("Path is a null reference.")
            Catch exp As System.Security.SecurityException
                System.Console.WriteLine("The caller does not have the " + _
                                           "required permission.")
            Catch exp As ArgumentException
                System.Console.WriteLine("Path is an empty string, " + _
                                        "contains only white spaces, " + _
                                        "or contains invalid characters.")
            Catch exp As System.IO.IOException
                System.Console.WriteLine("An attempt was made to move a " + _
                                        "directory to a different " + _
                                        "volume, or destDirName " + _
                                        "already exists.")
            End Try
        End Sub
    End Class
End Namespace

Комментарии

Порядок возвращаемых имен файлов и каталогов не гарантируется; используйте метод , Sort если требуется определенный порядок сортировки.

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

Описатель с подстановочным знаком Соответствует
* (звездочка) Ноль или более символов в этой позиции.
? (вопросительный знак) Ровно один символ в этой позиции.

Символы, отличные от подстановочного знака, являются литеральными символами. Например, searchPattern строка "*t" ищет все имена, path оканчивающиеся буквой "t". Строка searchPattern "s*" ищет все имена, path начинающиеся с буквы "s".

searchPattern не может заканчиваться двумя точками ("..") или содержать две точки (".."), за которыми следует DirectorySeparatorChar или AltDirectorySeparatorChar, и не может содержать недопустимые символы. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars.

Примечание

При использовании подстановочного знака звездочки в searchPattern таком объекте, как "*.txt", количество символов в указанном расширении влияет на поиск следующим образом:

  • Если указанное расширение имеет ровно три символа, метод возвращает файлы с расширениями, начинающимися с указанного расширения. Например, "*.xls" возвращает как "book.xls", так и "book.xlsx".
  • Во всех остальных случаях метод возвращает файлы, которые точно соответствуют указанному расширению. Например, "*.ai" возвращает "file.ai", но не "file.aif".

При использовании подстановочного знака вопросительного знака этот метод возвращает только файлы, соответствующие указанному расширению. Например, при использовании двух файлов, "file1.txt" и "file1.txtother", шаблон поиска "file?.txt" возвращает только первый файл, а шаблон поиска "file*.txt" возвращает оба файла.

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

Чувствительность параметра к регистру path соответствует значению файловой системы, в которой выполняется код. Например, регистр не учитывается в NTFS (файловая система Windows по умолчанию) и учитывает регистр в файловых системах Linux.

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

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

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

GetFileSystemEntries(String, String, EnumerationOptions)

Возвращает массив имен файлов и имен каталогов по указанному пути, соответствующих шаблону поиска и параметрам перечисления.

public:
 static cli::array <System::String ^> ^ GetFileSystemEntries(System::String ^ path, System::String ^ searchPattern, System::IO::EnumerationOptions ^ enumerationOptions);
public static string[] GetFileSystemEntries (string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions);
static member GetFileSystemEntries : string * string * System.IO.EnumerationOptions -> string[]
Public Shared Function GetFileSystemEntries (path As String, searchPattern As String, enumerationOptions As EnumerationOptions) As String()

Параметры

path
String

Относительный или абсолютный путь к каталогу для поиска. В этой строке не учитывается регистр знаков.

searchPattern
String

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

enumerationOptions
EnumerationOptions

Объект, описывающий конфигурацию поиска и перечисления для использования.

Возвращаемое значение

String[]

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

Исключения

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

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

-или-

searchPattern не содержит допустимый шаблон.

Параметр path или searchPattern имеет значение null.

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

path — это имя файла.

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

Комментарии

Порядок возвращаемых имен файлов и каталогов не гарантируется; используйте метод , Sort если требуется определенный порядок сортировки.

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

Описатель подстановочных знаков Соответствует
* (звездочка) Ноль или более символов в этой позиции.
? (вопросительный знак) Ровно один символ в этой позиции.

Символы, отличные от подстановочного знака, являются литеральными символами. Например, searchPattern строка "*t" ищет все имена, path заканчивающиеся буквой "t". Строка searchPattern "s*" ищет все имена, path начинающиеся с буквы "s".

searchPattern не может заканчиваться двумя точками ("..") или содержать две точки (".."), за которыми DirectorySeparatorChar следует или AltDirectorySeparatorChar, и не может содержать недопустимые символы. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars.

Примечание

При использовании подстановочного знака звездочки в searchPattern , например "*.txt", количество символов в указанном расширении влияет на поиск следующим образом:

  • Если указанное расширение имеет ровно три символа, метод возвращает файлы с расширениями, которые начинаются с указанного расширения. Например, "*.xls" возвращает "book.xls" и "book.xlsx".
  • Во всех остальных случаях метод возвращает файлы, которые точно соответствуют указанному расширению. Например, "*.ai" возвращает "file.ai", но не "file.aif".

При использовании подстановочного знака вопросительного знака этот метод возвращает только файлы, соответствующие указанному расширению файла. Например, при использовании двух файлов, "file1.txt" и "file1.txtother", в каталоге шаблон поиска "file?.txt" возвращает только первый файл, а шаблон поиска "file*.txt" возвращает оба файла.

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

Учет регистра path параметра соответствует значению файловой системы, в которой выполняется код. Например, регистр не учитывается в NTFS (файловая система Windows по умолчанию) и учитывается регистр в файловых системах Linux.

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

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

GetFileSystemEntries(String, String, SearchOption)

Возвращает массив всех имен файлов и каталогов по указанному пути, соответствующих шаблону поиска, и при необходимости ведет поиск в подкаталогах.

public:
 static cli::array <System::String ^> ^ GetFileSystemEntries(System::String ^ path, System::String ^ searchPattern, System::IO::SearchOption searchOption);
public static string[] GetFileSystemEntries (string path, string searchPattern, System.IO.SearchOption searchOption);
static member GetFileSystemEntries : string * string * System.IO.SearchOption -> string[]
Public Shared Function GetFileSystemEntries (path As String, searchPattern As String, searchOption As SearchOption) As String()

Параметры

path
String

Относительный или абсолютный путь к каталогу для поиска. В этой строке не учитывается регистр знаков.

searchPattern
String

Строка поиска, которая должна сравниваться с именами файлов и каталогов в параметре path. Этот параметр может содержать сочетание допустимого литерального пути и подстановочного символа (* и ?), но не поддерживает регулярные выражения.

searchOption
SearchOption

Одно из значений перечисления, определяющее, следует ли выполнять поиск только в текущем каталоге или также во всех его подкаталогах. Значение по умолчанию — TopDirectoryOnly.

Возвращаемое значение

String[]

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

Исключения

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

-или-

searchPattern не содержит допустимый шаблон.

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

-или-

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

searchOption не является допустимым значением SearchOption.

Недопустимый path: например, он ссылается на несопоставленный диск.

path — это имя файла.

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

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

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

Комментарии

Порядок возвращаемых имен файлов и каталогов не гарантируется; используйте метод , Sort если требуется определенный порядок сортировки.

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

Описатель подстановочных знаков Соответствует
* (звездочка) Ноль или более символов в этой позиции.
? (вопросительный знак) Ровно один символ в этой позиции.

Символы, отличные от подстановочного знака, являются литеральными символами. Например, searchPattern строка "*t" ищет все имена, path заканчивающиеся буквой "t". Строка searchPattern "s*" ищет все имена, path начинающиеся с буквы "s".

searchPattern не может заканчиваться двумя точками ("..") или содержать две точки (".."), за которыми DirectorySeparatorChar следует или AltDirectorySeparatorChar, и не может содержать недопустимые символы. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars.

Примечание

При использовании подстановочного знака звездочки в searchPattern , например "*.txt", количество символов в указанном расширении влияет на поиск следующим образом:

  • Если указанное расширение имеет ровно три символа, метод возвращает файлы с расширениями, которые начинаются с указанного расширения. Например, "*.xls" возвращает "book.xls" и "book.xlsx".
  • Во всех остальных случаях метод возвращает файлы, которые точно соответствуют указанному расширению. Например, "*.ai" возвращает "file.ai", но не "file.aif".

При использовании подстановочного знака вопросительного знака этот метод возвращает только файлы, соответствующие указанному расширению файла. Например, при использовании двух файлов, "file1.txt" и "file1.txtother", в каталоге шаблон поиска "file?.txt" возвращает только первый файл, а шаблон поиска "file*.txt" возвращает оба файла.

Методы EnumerateFileSystemEntries и GetFileSystemEntries отличаются следующим образом: при использовании EnumerateFileSystemEntriesможно начать перечисление коллекции записей до возвращения всей коллекции. При использовании GetFileSystemEntriesнеобходимо дождаться возвращения всего массива записей, прежде чем получить доступ к массиву. Таким образом, при работе с большим количеством файлов и каталогов EnumerateFileSystemEntries может быть более эффективным.

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

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

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