只有去除读取使用C#中的目录属性 [英] Removing read only attribute on a directory using C#

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

问题描述

我成功地能够删除只读使用以下code段属性上的一个文件:

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

在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);
}
}

不幸的是,这并不上的文件夹的工作。运行code后,当我去到该文件夹​​,右击并做性能,这里是我所看到的:

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:\test");
    ClearReadOnly(parentDirectoryInfo);
}

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

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