检查 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!
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP