在 C# 中检查文件是否存在
csharpprogrammingserver side programming更新于 2025/9/12 5:30:00
使用 C# 中的 File.exists 方法检查文件是否存在。
首先,检查文件是否存在于当前目录中。
if (File.Exists("MyFile.txt")) {
Console.WriteLine("The file exist.");
}
之后检查文件是否存在于目录中。
if (File.Exists(@"D:\myfile.txt")) {
Console.WriteLine("The file exist.");
}
让我们看一下在 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!

