C# 根据路径删除文件或文件夹
作者:野牛程序员:2023-12-25 13:31:27C#阅读 2966
使用System.IO命名空间中的File和Directory类可以根据路径删除文件或文件夹。以下是示例代码:
删除文件的代码:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "C:\\\\Path\\\\To\\\\Your\\\\File.txt";
// 检查文件是否存在
if (File.Exists(filePath))
{
// 删除文件
File.Delete(filePath);
Console.WriteLine("文件已删除");
}
else
{
Console.WriteLine("文件不存在");
}
}
}删除文件夹及其内容的代码:
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = "C:\\\\Path\\\\To\\\\Your\\\\Folder";
// 检查文件夹是否存在
if (Directory.Exists(folderPath))
{
// 删除文件夹及其内容
Directory.Delete(folderPath, true);
Console.WriteLine("文件夹已删除");
}
else
{
Console.WriteLine("文件夹不存在");
}
}
}请确保在使用这些代码时提供正确的文件或文件夹路径。删除文件时要小心,因为文件被删除后将无法恢复。删除文件夹时,如果第二个参数设置为 true,则会删除文件夹及其所有内容;如果设置为 false,则只删除空文件夹。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

