C#

[C#]파일 존재 여부 확인

DevStory 2022. 6. 6.

Exists() 메서드

C#에서 파일이 존재하는지 확인할 수 있는 몇 가지 방법이 존재합니다. 그중 가장 많이 사용하는 방법으로 System.IO 네임스페이스에 존재하는 File 클래스의 Exists() 메서드를 사용하는 것입니다.

if(File.Exists(file_path))
{
  // 파일이 존재하는 경우
}
else 
{
  // 파일이 존재하지 않는 경우
}
  • Exists() 메서드는 string 타입의 파일 경로를 매개 변수로 사용합니다.
  • 파일이 존재하면 true를 반환하고 파일이 없거나 접근할 수 있는 권한이 없으면 false를 반환합니다.
  • 경로가 유효하지 않거나 null 및 문자열 길이가 0인 경우에도 false를 반환합니다.

Exists() 메서드 예제

다음은 Exists() 메서드 예제에서 사용되는 파일입니다.


예제 1. 파일 존재 여부

다음 예제는 File.Exists() 메서드를 사용하여 파일 존재 여부를 확인합니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest\FileTest.txt";
    bool fileExist = File.Exists(path);
    
    if (fileExist)
    {
      Console.WriteLine("FileTest.txt 파일이 존재합니다.");
    }
    else
    {
      Console.WriteLine("FileTest.txt 파일을 찾을 수 없습니다.");
    }
  }
}

실행 결과

FileTest.txt 파일이 존재합니다.

예제 2. 폴더 존재 여부

이번 예제는 파일이 아닌 폴더 존재 여부를 확인합니다. 폴더는 File 클래스가 아닌 Directory 클래스의 Exists() 메서드를 사용합니다.

 

만약, 다음 예제처럼 File 클래스의 Exists() 메서드로 폴더 존재 여부를 확인하면 false가 반환됩니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest";
    bool dirExist = File.Exists(path);

    if (dirExist)
    {
      Console.WriteLine("FileTest 폴더가 존재합니다.");
    }
    else
    {
      Console.WriteLine("FileTest 폴더를 찾을 수 없습니다.");
    }
  }
}

실행 결과

FileTest 폴더를 찾을 수 없습니다.

다음 예제는 Directory 클래스의 Exists() 메서드를 사용합니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest";
    bool dirExist = Directory.Exists(path);

    if (dirExist)
    {
      Console.WriteLine("FileTest 폴더가 존재합니다.");
    }
    else
    {
      Console.WriteLine("FileTest 폴더를 찾을 수 없습니다.");
    }
  }
}

실행 결과

FileTest 폴더가 존재합니다.

예제 3. 폴더에 특정 파일 존재 여부

다음 예제는 FileTest 폴더의 정보를 읽은 후 Hello.txt 파일이 존재하는지 확인합니다.

class Program
{
  static void Main(string[] args)
  {
    string path = @"C:\FileTest";
    string filename = "Hello.txt";

    DirectoryInfo directory = new DirectoryInfo(path);
    FileInfo[] files = directory.GetFiles();

    bool fileFound = false;
    foreach (FileInfo file in files)
    {
      if (String.Compare(file.Name, filename) == 0)
      {
        fileFound = true;
        Console.WriteLine("Hello.txt 파일이 존재합니다.");
      }
    }

    if (!fileFound)
    {
      Console.WriteLine("Hello.txt 파일이 존재하지 않습니다.");
    }
  }
}

실행 결과

Hello.txt 파일이 존재하지 않습니다.

정리

  • 파일 존재 여부는 File 클래스의 Exists() 메서드를 사용하여 확인할 수 있습니다.
  • 폴더 존재 여부는 Directory 클래스의 Exists() 메서드를 사용하여 확인할 수 있습니다.
  • File 클래스와 Directory 클래스는 System.IO 네임스페이스에 존재합니다.
  • 파일 및 폴더가 존재하면 true, 그렇지 않으면 false가 반환됩니다.
반응형

'C#' 카테고리의 다른 글

[C#]스레드 Join 메서드(Join Method of Thread)  (0) 2022.06.15
[C#]스레드 상태 확인  (0) 2022.06.06
[C#]base 키워드  (0) 2022.06.05
[C#]잠금 및 Lock 키워드  (0) 2022.06.05
[C#]스레드 동기화(Thread Synchronization)  (0) 2022.06.05

댓글