在 C# 中删除一个文件

本教程将介绍删除 C# 中特定路径的文件的方法。

在 C# 中使用 File.Delete(path) 函数删除文件

在 C# 中,File.Delete(path) 函数用于删除 path 路径内的文件。以下代码示例向我们展示了如何使用 C# 中的 File.Delete() 函数从指定路径删除文件。

using System;
using System.IO;
namespace check_whether_a_file_exists
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "C:\\filefolder\\file.txt";
            bool result = File.Exists(path);
            if (result == true)
            {
                Console.WriteLine("File Found");
                File.Delete(path);
                Console.WriteLine("File Deleted Successfully");
            }
            else
            {
                Console.WriteLine("File Not Found");
            }
        }
    }
}

输出:

File Found
File Deleted Successfully

我们使用 C# 中的 File.Delete() 函数删除了 C:\\filefolder\\file.txt 路径内的文件。我们的程序首先使用 File.Exists() 函数检查 path 内是否存在文件。如果文件存在,程序将使用 File.Delete() 函数删除该文件。如果文件不存在,程序将显示 File Not Found