C# 根据路径删除文件或文件夹

如何根据路径删除文件或文件夹?

1.首先我们要判断路径是文件或者是文件夹

那么我们可以通过 FileAttributes attr = File.GetAttributes(path); 来得到路径的属性

在判断属性是否是FileAttributes.Directory

完整代码

    /// <summary>
    /// 根据路径删除文件
    /// </summary>
    /// <param name="path"></param>
    public void DeleteFile(string path)
    {
        FileAttributes attr = File.GetAttributes(path);
        if (attr == FileAttributes.Directory)
        {
            Directory.Delete(path, true);
        }
        else
        {
            File.Delete(path);
        }
    }