檢查 C# 中的檔案是否存在


在 C# 中使用 File.exists 方法檢查檔案在 C# 中是否存在。

首先,檢查檔案是否存在於當前目錄中。

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

然後檢查檔案是否存在於目錄中。

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

我們來看看一個完整的示例,檢查檔案是否存在於 C# 中。

示例

 線上演示

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!");
      }
   }
}

輸出

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

更新日期:2020 年 6 月 23 日

9,000 次瀏覽

開啟您的職業

透過完成課程取得認證

開始
廣告
© . All rights reserved.