使用 C# 删除目录上的只读属性 [英] Removing read only attribute on a directory using C#

查看:24
本文介绍了使用 C# 删除目录上的只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码片段成功删除了文件的只读属性:

I was successfully able to remove read only attribute on a file using the following code snippet:

在 main.cs 中

In main.cs

FileSystemInfo[] sqlParentFileSystemInfo = dirInfo.GetFileSystemInfos();

foreach (var childFolderOrFile in sqlParentFileSystemInfo)
{
    RemoveReadOnlyFlag(childFolderOrFile);
}

private static void RemoveReadOnlyFlag(FileSystemInfo fileSystemInfo)
{
    fileSystemInfo.Attributes = FileAttributes.Normal;
    var di = fileSystemInfo as DirectoryInfo;

    if (di != null)
    {
        foreach (var dirInfo in di.GetFileSystemInfos())
            RemoveReadOnlyFlag(dirInfo);
    }
}

不幸的是,这不适用于文件夹.运行代码后,当我进入文件夹时,右键单击并执行属性,这是我看到的:

Unfortunately, this doesn't work on the folders. After running the code, when I go to the folder, right click and do properties, here's what I see:

只读标志仍然被检查,尽管它从它下面的文件中删除了它.这会导致进程无法删除此文件夹.当我手动删除标志并重新运行该进程(一个 bat 文件)时,它能够删除该文件(所以我知道这不是 bat 文件的问题)

The read only flag is still checked although it removed it from files underneath it. This causes a process to fail deleting this folder. When I manually remove the flag and rerun the process (a bat file), it's able to delete the file (so I know this is not an issue with the bat file)

如何在 C# 中删除此标志?

How do I remove this flag in C#?

推荐答案

您还可以执行以下操作,以递归方式清除指定父目录中所有目录和文件的只读(和存档等):

You could also do something like the following to recursively clear readonly (and archive, etc.) for all directories and files within a specified parent directory:

private void ClearReadOnly(DirectoryInfo parentDirectory)
{
    if(parentDirectory != null)
    {
        parentDirectory.Attributes = FileAttributes.Normal;
        foreach (FileInfo fi in parentDirectory.GetFiles())
        {
            fi.Attributes = FileAttributes.Normal;
        }
        foreach (DirectoryInfo di in parentDirectory.GetDirectories())
        {
            ClearReadOnly(di);
        }
    }
}

因此你可以这样称呼它:

You can therefore call this like so:

public void Main()
{
    DirectoryInfo parentDirectoryInfo = new DirectoryInfo(@"c:	est");
    ClearReadOnly(parentDirectoryInfo);
}

这篇关于使用 C# 删除目录上的只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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