Computer >> Máy Tính >  >> Lập trình >> C#

Kiểm tra xem Tệp có tồn tại trong C # hay không

Sử dụng phương thức File.exists trong C # để kiểm tra xem tệp có thoát trong C # hay không.

Trước tiên, hãy kiểm tra xem tệp có trong thư mục hiện tại hay không.

if (File.Exists("MyFile.txt")) {
   Console.WriteLine("The file exists.");
}

Sau đó, hãy kiểm tra xem tệp có tồn tại trong một thư mục hay không.

if (File.Exists(@"D:\myfile.txt")) {
   Console.WriteLine("The file exists.");
}

Hãy để chúng tôi xem ví dụ đầy đủ để kiểm tra xem tệp có tồn tại trong C # hay không.

Ví dụ

using System;
using System.IO;
class Demo {
   static void Main() {
      if (File.Exists("MyFile.txt")) {
         Console.WriteLine("File exists...");
      } else {
         Console.WriteLine("File does not exist in the current directory!");
      }
      if (File.Exists(@"D:\myfile.txt")) {
         Console.WriteLine("File exists...");
      } else {
         Console.WriteLine("File does not exist in the D directory!");
      }
   }
}

Đầu ra

File does not exist in the current directory!
File does not exist in the D directory!