答案:使用File.Exists和Directory.Exists可判断文件或文件夹是否存在。File.Exists检查文件路径返回布尔值,Directory.Exists检查目录路径同样返回布尔值,两者均需正确处理路径格式与异常情况。

在 .NET 中判断文件或文件夹是否存在,主要使用 System.IO 命名空间下的两个类:File 和 Directory。它们提供了静态方法来快速检查路径对应的文件或目录是否存在。
使用 File.Exists(string path) 方法可以判断指定路径的文件是否存在。该方法返回布尔值,存在则返回 true,否则返回 false。
示例代码:
string filePath = @"C:\example\test.txt";
if (File.Exists(filePath))
{
Console.WriteLine("文件存在");
}
else
{
Console.WriteLine("文件不存在");
}
使用 Directory.Exists(string path) 方法判断指定路径的目录是否存在。同样返回布尔值。
示例代码:
string folderPath = @"C:\example\myfolder";
if (Directory.Exists(folderPath))
{
Console.WriteLine("文件夹存在");
}
else
{
Console.WriteLine("文件夹不存在");
}