如何在 C# 中删除包含只读文件的目录? [英] How do I delete a directory with read-only files in C#?

查看:23
本文介绍了如何在 C# 中删除包含只读文件的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除一个包含只读文件的目录.哪种方法更好:

I need to delete a directory that contains read-only files. Which approach is better:

  • 使用DirectoryInfo.Delete(),或者,

ManagementObject.InvokeMethod("Delete")?

使用 DirectoryInfo.Delete(),我必须手动关闭每个文件的只读属性,但是 ManagementObject.InvokeMethod("Delete") 没有似乎不需要.有没有一种情况比另一种更可取的情况?

With DirectoryInfo.Delete(), I have to manually turn off the read-only attribute for each file, but ManagementObject.InvokeMethod("Delete") doesn't appear to need to. Is there any situation where one is more preferable to the other?

示例代码(test.txt 是只读的).

Sample code (test.txt is read only).

DirectoryInfo dir = new DirectoryInfo(@"C:UsersDavidDesktop");
dir.CreateSubdirectory("Test");

DirectoryInfo test = new DirectoryInfo(@"C:UsersDavidDesktopTest");
File.Copy(@"C:UsersDavidDesktop	est.txt", @"C:UsersDavidDesktopTest	est.txt");
File.SetAttributes(@"C:UsersDavidDesktopTest	est.txt", FileAttributes.Archive);
test.Delete(true);

第二种方式:

DirectoryInfo dir = new DirectoryInfo(@"C:UsersDavidDesktop");
dir.CreateSubdirectory("Test");

DirectoryInfo test = new DirectoryInfo(@"C:UsersDavidDesktopTest");
File.Copy(@"C:UsersDavidDesktop	est.txt", @"C:UsersDavidDesktopTest	est.txt");

string folder = @"C:UsersDavidDesktopTest";
string dirObject = "Win32_Directory.Name='" + folder + "'";
using (ManagementObject managementObject = new ManagementObject(dirObject))
{
    managementObject.Get();
    ManagementBaseObject outParams = managementObject.InvokeMethod("Delete", null,
    null);
    // ReturnValue should be 0, else failure
    if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0)
    {
    }
}

推荐答案

这是一个扩展方法,它递归地将 Attributes 设置为 Normal,然后删除项目:

Here is an extension method which sets Attributes to Normal recursively, then deletes the items:

public static void DeleteReadOnly(this FileSystemInfo fileSystemInfo)
{
    var directoryInfo = fileSystemInfo as DirectoryInfo;    
    if (directoryInfo != null)
    {
        foreach (FileSystemInfo childInfo in directoryInfo.GetFileSystemInfos())
        {
            childInfo.DeleteReadOnly();
        }
    }

    fileSystemInfo.Attributes = FileAttributes.Normal;
    fileSystemInfo.Delete();
}

这篇关于如何在 C# 中删除包含只读文件的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆