Directory.GetFiles 메서드

정의

지정된 조건을 충족하는 파일 이름을 반환합니다.

오버로드

GetFiles(String)

지정된 디렉터리에 있는 파일의 이름(경로 포함)을 반환합니다.

GetFiles(String, String)

지정된 디렉터리에서 지정된 검색 패턴과 일치하는 파일 이름(파일 경로 포함)을 반환합니다.

GetFiles(String, String, EnumerationOptions)

지정된 디렉터리에서 지정된 검색 패턴 및 열거형 옵션과 일치하는 파일 이름(파일 경로 포함)을 반환합니다.

GetFiles(String, String, SearchOption)

하위 디렉터리를 검색할지를 나타내는 값을 사용하여 지정된 디렉터리에서 지정된 검색 패턴과 일치하는 파일 이름(파일 경로 포함)을 반환합니다.

GetFiles(String)

Source:
Directory.cs
Source:
Directory.cs
Source:
Directory.cs

지정된 디렉터리에 있는 파일의 이름(경로 포함)을 반환합니다.

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

매개 변수

path
String

검색할 디렉터리에 대한 상대 또는 절대 경로입니다. 이 문자열은 대/소문자를 구분하지 않습니다.

반환

String[]

지정된 디렉터리에서 파일의 전체 이름(경로 포함)의 배열이거나 파일이 없으면 빈 배열입니다.

예외

path는 파일 이름입니다.

또는

네트워크 오류가 발생했습니다.

호출자에게 필요한 권한이 없는 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

path이(가) null인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

지정된 경로가 없거나 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

예제

다음 예제에서는 메서드를 사용 하 여 GetFiles 사용자 지정 된 위치에서 파일 이름을 반환 하는 방법을 보여 줍니다. 이 예제는 이 메서드에 공통된 모든 오류를 catch하도록 구성됩니다.

// For Directory::GetFiles and Directory::GetDirectories
// For File::Exists, Directory::Exists
using namespace System;
using namespace System::IO;
using namespace System::Collections;

// Insert logic for processing found files here.
void ProcessFile( String^ path )
{
   Console::WriteLine( "Processed file '{0}'.", path );
}


// Process all files in the directory passed in, recurse on any directories 
// that are found, and process the files they contain.
void ProcessDirectory( String^ targetDirectory )
{
   
   // Process the list of files found in the directory.
   array<String^>^fileEntries = Directory::GetFiles( targetDirectory );
   IEnumerator^ files = fileEntries->GetEnumerator();
   while ( files->MoveNext() )
   {
      String^ fileName = safe_cast<String^>(files->Current);
      ProcessFile( fileName );
   }

   
   // Recurse into subdirectories of this directory.
   array<String^>^subdirectoryEntries = Directory::GetDirectories( targetDirectory );
   IEnumerator^ dirs = subdirectoryEntries->GetEnumerator();
   while ( dirs->MoveNext() )
   {
      String^ subdirectory = safe_cast<String^>(dirs->Current);
      ProcessDirectory( subdirectory );
   }
}

int main( int argc, char *argv[] )
{
   for ( int i = 1; i < argc; i++ )
   {
      String^ path = gcnew String(argv[ i ]);
      if ( File::Exists( path ) )
      {
         
         // This path is a file
         ProcessFile( path );
      }
      else
      if ( Directory::Exists( path ) )
      {
         
         // This path is a directory
         ProcessDirectory( path );
      }
      else
      {
         Console::WriteLine( "{0} is not a valid file or directory.", path );
      }

   }
}
// For Directory.GetFiles and Directory.GetDirectories
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor
{
    public static void Main(string[] args)
    {
        foreach(string path in args)
        {
            if(File.Exists(path))
            {
                // This path is a file
                ProcessFile(path);
            }
            else if(Directory.Exists(path))
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }
        }
    }

    // Process all files in the directory passed in, recurse on any directories
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path)
    {
        Console.WriteLine("Processed file '{0}'.", path);	
    }
}
module RecursiveFileProcessor

open System.IO

// Insert logic for processing found files here.
let processFile path =
    printfn $"Processed file '%s{path}'."

// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
let rec processDirectory targetDirectory =
    // Process the list of files found in the directory.
    let fileEntries = Directory.GetFiles targetDirectory
    for fileName in fileEntries do
        processFile fileName

    // Recurse into subdirectories of this directory.
    let subdirectoryEntries = Directory.GetDirectories targetDirectory
    for subdirectory in subdirectoryEntries do
        processDirectory subdirectory

[<EntryPoint>]
let main args =
    for path in args do
        if File.Exists path then
            // This path is a file
            processFile path
        elif Directory.Exists path then
            // This path is a directory
            processDirectory path
        else
            printfn $"{path} is not a valid file or directory."
    0
' For Directory.GetFiles and Directory.GetDirectories
' For File.Exists, Directory.Exists 

Imports System.IO
Imports System.Collections

Public Class RecursiveFileProcessor

    Public Overloads Shared Sub Main(ByVal args() As String)
        Dim path As String
        For Each path In args
            If File.Exists(path) Then
                ' This path is a file.
                ProcessFile(path)
            Else
                If Directory.Exists(path) Then
                    ' This path is a directory.
                    ProcessDirectory(path)
                Else
                    Console.WriteLine("{0} is not a valid file or directory.", path)
                End If
            End If
        Next path
    End Sub


    ' Process all files in the directory passed in, recurse on any directories 
    ' that are found, and process the files they contain.
    Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
        Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
        ' Process the list of files found in the directory.
        Dim fileName As String
        For Each fileName In fileEntries
            ProcessFile(fileName)

        Next fileName
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
        ' Recurse into subdirectories of this directory.
        Dim subdirectory As String
        For Each subdirectory In subdirectoryEntries
            ProcessDirectory(subdirectory)
        Next subdirectory

    End Sub

    ' Insert logic for processing found files here.
    Public Shared Sub ProcessFile(ByVal path As String)
        Console.WriteLine("Processed file '{0}'.", path)
    End Sub
End Class

설명

및 메서드는 EnumerateFiles 다음과 같이 다릅니다. 를 사용하면 EnumerateFiles전체 컬렉션이 반환되기 전에 이름 컬렉션을 열거할 수 있습니다. 를 사용하는 GetFiles경우 전체 이름 배열이 반환될 때까지 기다려야 배열에 액세스할 수 GetFiles 있습니다. 따라서 많은 파일 및 디렉터리 EnumerateFiles 로 작업할 때 보다 효율적일 수 있습니다.

반환된 파일 이름은 제공 path 된 매개 변수에 추가됩니다.

이 메서드는 검색 패턴으로 지정된 별표(*)와 동일합니다 GetFiles(String, String) .

매개 변수는 path 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

반환된 파일 이름의 순서는 보장되지 않습니다. 특정 정렬 순서가 Sort 필요한 경우 메서드를 사용합니다.

매개 변수의 path 대/소문자 구분은 코드가 실행 중인 파일 시스템의 대/소문자 구분에 해당합니다. 예를 들어 NTFS(기본 Windows 파일 시스템)에서는 대/소문자를 구분하지 않으며 Linux 파일 시스템에서는 대/소문자를 구분합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

GetFiles(String, String)

Source:
Directory.cs
Source:
Directory.cs
Source:
Directory.cs

지정된 디렉터리에서 지정된 검색 패턴과 일치하는 파일 이름(파일 경로 포함)을 반환합니다.

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

매개 변수

path
String

검색할 디렉터리에 대한 상대 또는 절대 경로입니다. 이 문자열은 대/소문자를 구분하지 않습니다.

searchPattern
String

path에 있는 파일 이름과 일치하는지 비교할 검색 문자열입니다. 이 매개 변수는 유효한 리터럴 경로와 와일드카드(* 및 ?) 문자로 된 조합을 포함하지만 정규식을 지원하지 않습니다.

반환

String[]

지정된 디렉터리에서 지정된 검색 패턴과 일치하는 파일의 전체 이름(경로 포함)의 배열이거나 파일이 없으면 빈 배열입니다.

예외

path는 파일 이름입니다.

또는

네트워크 오류가 발생했습니다.

호출자에게 필요한 권한이 없는 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars()를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

searchPattern에 유효한 패턴이 포함되어 있지 않습니다.

path 또는 searchPatternnull인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

지정된 경로가 없거나 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

예제

다음 예제에서는 지정된 문자로 시작하는 파일 수를 계산합니다.

using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      
      // Only get files that begin with the letter "c".
      array<String^>^dirs = Directory::GetFiles( "c:\\", "c*" );
      Console::WriteLine( "The number of files starting with c is {0}.", dirs->Length );
      Collections::IEnumerator^ myEnum = dirs->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Console::WriteLine( myEnum->Current );
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }

}
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Only get files that begin with the letter "c".
            string[] dirs = Directory.GetFiles(@"c:\", "c*");
            Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
            foreach (string dir in dirs)
            {
                Console.WriteLine(dir);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
open System.IO

try
    // Only get files that begin with the letter "c".
    let dirs = Directory.GetFiles(@"c:\", "c*")
    printfn $"The number of files starting with c is {dirs.Length}."
    for dir in dirs do
        printfn $"{dir}"
with e ->
    printfn $"The process failed: {e}"
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        Try
            ' Only get files that begin with the letter "c".
            Dim dirs As String() = Directory.GetFiles("c:\", "c*")
            Console.WriteLine("The number of files starting with c is {0}.", dirs.Length)
            Dim dir As String
            For Each dir In dirs
                Console.WriteLine(dir)
            Next
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

설명

반환된 파일 이름은 제공 path 된 매개 변수에 추가되고 반환된 파일 이름의 순서는 보장되지 않습니다. 특정 정렬 순서가 필요한 경우 메서드를 사용합니다 Sort .

searchPattern 는 리터럴과 와일드카드 문자의 조합일 수 있지만 정규식을 지원하지는 않습니다. 에서 허용되는 와일드카드 지정자는 다음과 같습니다 searchPattern.

와일드카드 지정자 일치하는 항목
*(별표) 해당 위치에 0개 이상의 문자가 있습니다.
? (물음표) 정확히 그 위치에 있는 한 문자입니다.

와일드카드 이외의 문자는 리터럴 문자입니다. 예를 들어 searchPattern 문자열 "*t"는 문자 "t"로 끝나는 의 모든 이름을 path 검색합니다. 문자열 "s*"는 searchPattern 문자 "s"로 path 시작하는 의 모든 이름을 검색합니다.

searchPattern 는 두 개의 마침표("..")로 끝나거나 두 개의 마침표("..") 뒤에 DirectorySeparatorChar 또는 AltDirectorySeparatorChar를 포함할 수 없으며 잘못된 문자를 포함할 수도 없습니다. GetInvalidPathChars 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

참고

.NET Framework 전용: 에서 별표 와일드카드 문자를 searchPattern 사용하고 3자 파일 확장명(예: "*.txt")을 지정하는 경우 이 메서드는 지정된 확장명으로 시작하는 확장명을 가진 파일도 반환합니다. 예를 들어 검색 패턴 "*.xls"은 "book.xls" 및 "book.xlsx"를 모두 반환합니다. 이 동작은 검색 패턴에서 별표가 사용되고 제공된 파일 확장자가 정확히 3자인 경우에만 발생합니다. 검색 패턴의 어딘가에 물음표 와일드카드 문자를 사용하는 경우 이 메서드는 지정된 파일 확장명확인과 정확히 일치하는 파일만 반환합니다. 다음 표에서는 .NET Framework 이 변칙을 보여 줍니다.

디렉터리의 파일 검색 패턴 .NET 5 이상 반환 .NET Framework 반환
file.ai, file.aif *.Ai file.ai file.ai
book.xls, book.xlsx *.xls book.xls book.xls, book.xlsx
ello.txt, hello.txt, hello.txtt ?ello.txt ello.txt, hello.txt ello.txt, hello.txt

참고

이 메서드는 8.3 파일 이름 형식과 긴 파일 이름 형식을 모두 사용하여 파일 이름을 확인하므로 "*1*.txt"과 유사한 검색 패턴은 예기치 않은 파일 이름을 반환할 수 있습니다. 예를 들어 "*1*.txt"의 검색 패턴을 사용하면 해당 8.3 파일 이름 형식이 "LONGFI~1.TXT"이므로 "longfilename.txt"가 반환됩니다.

및 메서드는 EnumerateFiles 다음과 같이 다릅니다. 를 사용하면 EnumerateFiles전체 컬렉션이 반환되기 전에 이름 컬렉션을 열거할 수 있습니다. 를 사용하는 GetFiles경우 전체 이름 배열이 반환될 때까지 기다려야 배열에 액세스할 수 GetFiles 있습니다. 따라서 많은 파일 및 디렉터리 EnumerateFiles 로 작업할 때 보다 효율적일 수 있습니다.

매개 변수는 path 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

매개 변수의 path 대/소문자 구분은 코드가 실행 중인 파일 시스템의 대/소문자 구분에 해당합니다. 예를 들어 NTFS(기본 Windows 파일 시스템)에서는 대/소문자를 구분하지 않으며 Linux 파일 시스템에서는 대/소문자를 구분합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

GetFiles(String, String, EnumerationOptions)

Source:
Directory.cs
Source:
Directory.cs
Source:
Directory.cs

지정된 디렉터리에서 지정된 검색 패턴 및 열거형 옵션과 일치하는 파일 이름(파일 경로 포함)을 반환합니다.

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

매개 변수

path
String

검색할 디렉터리에 대한 상대 또는 절대 경로입니다. 이 문자열은 대/소문자를 구분하지 않습니다.

searchPattern
String

path에 있는 하위 디렉터리 이름과 일치하는지 비교할 검색 문자열입니다. 이 매개 변수는 유효한 리터럴 및 와일드카드 문자로 된 조합을 포함하지만 정규식을 지원하지 않습니다.

enumerationOptions
EnumerationOptions

사용할 검색 및 열거형 구성을 설명하는 개체입니다.

반환

String[]

지정된 디렉터리에서 지정된 검색 패턴 및 열거형 옵션과 일치하는 파일의 전체 이름(경로 포함)의 배열이거나 파일이 없으면 빈 배열입니다.

예외

path는 파일 이름입니다.

또는

네트워크 오류가 발생했습니다.

호출자에게 필요한 권한이 없는 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars()를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

searchPattern에 유효한 패턴이 포함되어 있지 않습니다.

path 또는 searchPatternnull인 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

지정된 경로가 없거나 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

설명

반환된 파일 이름은 제공 path 된 매개 변수에 추가되며 반환된 파일 이름의 순서는 보장되지 않습니다. 특정 정렬 순서가 필요한 경우 메서드를 사용합니다 Sort .

searchPattern 는 리터럴 문자와 와일드카드 문자의 조합일 수 있지만 정규식을 지원하지는 않습니다. 에서 허용되는 와일드카드 지정자는 다음과 같습니다 searchPattern.

와일드카드 지정자 일치하는 항목
*(별표) 해당 위치에 0개 이상의 문자가 있습니다.
? (물음표) 해당 위치에 정확히 한 문자가 있습니다.

와일드카드 이외의 문자는 리터럴 문자입니다. 예를 들어 searchPattern 문자열 "*t"는 문자 "t"로 끝나는 의 모든 이름을 path 검색합니다. 문자열 "s*"는 searchPattern 문자 "s"로 path 시작하는 의 모든 이름을 검색합니다.

searchPattern 는 두 개의 마침표("..")로 끝나거나 두 개의 마침표("..") 뒤에 DirectorySeparatorChar 또는 AltDirectorySeparatorChar를 포함할 수 없으며 잘못된 문자를 포함할 수도 없습니다. GetInvalidPathChars 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

참고

.NET Framework 전용: 에서 searchPattern 별표 와일드카드 문자를 사용하고 3자 파일 확장명(예: "*.txt")을 지정하는 경우 이 메서드는 지정된 확장으로 시작하는 확장명을 가진 파일도 반환합니다. 예를 들어 검색 패턴 "*.xls"은 "book.xls" 및 "book.xlsx"를 모두 반환합니다. 이 동작은 검색 패턴에서 별표가 사용되고 제공된 파일 확장자가 정확히 3자인 경우에만 발생합니다. 검색 패턴의 어딘가에 물음표 와일드카드 문자를 사용하는 경우 이 메서드는 지정된 파일 확장명과 정확히 일치하는 파일만 반환합니다. 다음 표에서는 .NET Framework 이 변칙을 보여 줍니다.

디렉터리의 파일 검색 패턴 .NET 5+ 반환 .NET Framework 반환
file.ai, file.aif *.Ai file.ai file.ai
book.xls, book.xlsx *.xls book.xls book.xls, book.xlsx
ello.txt, hello.txt, hello.txtt ?ello.txt ello.txt, hello.txt ello.txt, hello.txt

참고

이 메서드는 8.3 파일 이름 형식과 긴 파일 이름 형식을 모두 사용하여 파일 이름을 확인하므로 "*1*.txt"과 유사한 검색 패턴은 예기치 않은 파일 이름을 반환할 수 있습니다. 예를 들어 "*1*.txt"의 검색 패턴을 사용하면 해당하는 8.3 파일 이름 형식이 "LONGFI~1.TXT"이므로 "longfilename.txt"이 반환됩니다.

및 메서드는 EnumerateFiles 다음과 같이 다릅니다. 를 사용하면 EnumerateFiles전체 컬렉션이 반환되기 전에 이름 컬렉션을 열거할 수 있습니다. 를 사용하는 GetFiles경우 전체 이름 배열이 반환될 때까지 기다려야 배열에 액세스할 수 GetFiles 있습니다. 따라서 많은 파일 및 디렉터리 EnumerateFiles 로 작업할 때 보다 효율적일 수 있습니다.

매개 변수는 path 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

매개 변수의 path 대/소문자 구분은 코드가 실행 중인 파일 시스템의 대/소문자 구분에 해당합니다. 예를 들어 NTFS(기본 Windows 파일 시스템)에서는 대/소문자를 구분하지 않으며 Linux 파일 시스템에서는 대/소문자를 구분합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

적용 대상

GetFiles(String, String, SearchOption)

Source:
Directory.cs
Source:
Directory.cs
Source:
Directory.cs

하위 디렉터리를 검색할지를 나타내는 값을 사용하여 지정된 디렉터리에서 지정된 검색 패턴과 일치하는 파일 이름(파일 경로 포함)을 반환합니다.

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

매개 변수

path
String

검색할 디렉터리에 대한 상대 또는 절대 경로입니다. 이 문자열은 대/소문자를 구분하지 않습니다.

searchPattern
String

path에 있는 파일 이름과 일치하는지 비교할 검색 문자열입니다. 이 매개 변수는 유효한 리터럴 경로와 와일드카드(* 및 ?) 문자로 된 조합을 포함하지만 정규식을 지원하지 않습니다.

searchOption
SearchOption

검색 작업에 현재 디렉터리만 포함할지 아니면 모든 하위 디렉터리를 포함할지를 지정하는 열거형 값 중 하나입니다.

반환

String[]

지정된 디렉터리에서 지정된 검색 패턴 및 옵션과 일치하는 파일의 전체 이름(경로 포함)의 배열이거나 파일이 없으면 빈 배열입니다.

예외

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

searchPattern에 유효한 패턴이 포함되어 있지 않습니다.

path 또는 searchpatternnull인 경우

searchOption는 유효한 SearchOption 값이 아닙니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 없거나 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

path는 파일 이름입니다.

또는

네트워크 오류가 발생했습니다.

설명

반환된 파일 이름은 제공된 매개 변수 path 에 추가되며 반환된 파일 이름의 순서는 보장되지 않습니다. 특정 정렬 순서가 필요한 경우 메서드를 사용합니다 Sort .

searchPattern 는 리터럴 문자와 와일드카드 문자의 조합일 수 있지만 정규식을 지원하지는 않습니다. 에서 허용되는 와일드카드 지정자는 다음과 같습니다 searchPattern.

와일드카드 지정자 일치하는 항목
*(별표) 해당 위치에 0개 이상의 문자가 있습니다.
? (물음표) 해당 위치에 정확히 한 문자가 있습니다.

와일드카드 이외의 문자는 리터럴 문자입니다. 예를 들어 searchPattern 문자열 "*t"는 문자 "t"로 끝나는 의 모든 이름을 path 검색합니다. 문자열 "s*"는 searchPattern 문자 "s"로 path 시작하는 의 모든 이름을 검색합니다.

searchPattern 는 두 개의 마침표("..")로 끝나거나 두 개의 마침표("..") 뒤에 DirectorySeparatorChar 또는 AltDirectorySeparatorChar를 포함할 수 없으며 잘못된 문자를 포함할 수도 없습니다. GetInvalidPathChars 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

참고

.NET Framework 전용: 에서 별표 와일드카드 문자를 searchPattern 사용하고 3자 파일 확장명(예: "*.txt")을 지정하는 경우 이 메서드는 지정된 확장명으로 시작하는 확장명을 가진 파일도 반환합니다. 예를 들어 검색 패턴 "*.xls"은 "book.xls" 및 "book.xlsx"를 모두 반환합니다. 이 동작은 검색 패턴에서 별표가 사용되고 제공된 파일 확장자가 정확히 3자인 경우에만 발생합니다. 검색 패턴의 어딘가에 물음표 와일드카드 문자를 사용하는 경우 이 메서드는 지정된 파일 확장명확인과 정확히 일치하는 파일만 반환합니다. 다음 표에서는 .NET Framework 이 변칙을 보여 줍니다.

디렉터리의 파일 검색 패턴 .NET 5 이상 반환 .NET Framework 반환
file.ai, file.aif *.Ai file.ai file.ai
book.xls, book.xlsx *.xls book.xls book.xls, book.xlsx
ello.txt, hello.txt, hello.txtt ?ello.txt ello.txt, hello.txt ello.txt, hello.txt

참고

이 메서드는 8.3 파일 이름 형식과 긴 파일 이름 형식을 모두 사용하여 파일 이름을 확인하므로 "*1*.txt"과 유사한 검색 패턴은 예기치 않은 파일 이름을 반환할 수 있습니다. 예를 들어 "*1*.txt"의 검색 패턴을 사용하면 해당 8.3 파일 이름 형식이 "LONGFI~1.TXT"이므로 "longfilename.txt"가 반환됩니다.

및 메서드는 EnumerateFiles 다음과 같이 다릅니다. 를 사용하면 EnumerateFiles전체 컬렉션이 반환되기 전에 이름 컬렉션을 열거할 수 있습니다. 를 사용하는 GetFiles경우 전체 이름 배열이 반환될 때까지 기다려야 배열에 액세스할 수 GetFiles 있습니다. 따라서 많은 파일 및 디렉터리 EnumerateFiles 로 작업할 때 보다 효율적일 수 있습니다.

파일 이름에는 전체 경로가 포함됩니다.

매개 변수는 path 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

매개 변수의 path 대/소문자 구분은 코드가 실행 중인 파일 시스템의 대/소문자 구분에 해당합니다. 예를 들어 NTFS(기본 Windows 파일 시스템)에서는 대/소문자를 구분하지 않으며 Linux 파일 시스템에서는 대/소문자를 구분합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상