只有去除读取使用C#中的目录属性属性、目录

由网友(你滚吧!)分享简介:我成功地能够删除只读使用以下code段属性上的一个文件:I was successfully able to remove read only attribute on a file using the following code snippet:在main.cs FileSystemInfo[] sqlPar...

我成功地能够删除只读使用以下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);
}
阅读全文

相关推荐

最新文章