Directory.Exists(String) 메서드

정의

지정된 경로가 디스크에 있는 기존 디렉터리를 참조하는지를 확인합니다.

public:
 static bool Exists(System::String ^ path);
public static bool Exists (string path);
public static bool Exists (string? path);
static member Exists : string -> bool
Public Shared Function Exists (path As String) As Boolean

매개 변수

path
String

테스트할 경로입니다.

반환

path가 기존 디렉터리를 참조하면 true이고, 디렉터리가 존재하지 않거나 지정된 디렉터리가 존재하는지 확인할 때 오류가 발생하면 false입니다.

예제

다음 예제에서는 명령줄에서 파일 또는 디렉터리 이름의 배열을 사용하고, 이름 종류를 결정하고, 적절하게 처리합니다.

// 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 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 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

설명

path 매개 변수는 상대 경로 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다.

디렉터리가 있는지 확인하기 전에 매개 변수의 path 끝에서 후행 공백이 제거됩니다.

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

디렉터리에 대한 최소 읽기 전용 권한이 없는 경우 메서드는 Exists 를 반환 false합니다.

메서드는 Exists 지정된 파일이 있는지 확인하는 동안 오류가 발생하면 를 반환 false 합니다. 잘못된 문자 또는 너무 많은 문자로 파일 이름을 전달하거나, 실패하거나 누락된 디스크를 사용하거나, 호출자에게 파일을 읽을 수 있는 권한이 없는 경우와 같은 예외가 발생하는 경우에 발생할 수 있습니다.

적용 대상

추가 정보