Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing read only attribute on a directory using C#

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

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:

alt text

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)

How do I remove this flag in C#?

like image 524
DotnetDude Avatar asked Oct 05 '10 19:10

DotnetDude


People also ask

How do I remove read only?

Remove the read-only attributeRight-click the file and select Properties. Uncheck the box for Read-only and click OK.

How do I delete read only files in CMD?

If you don't see the Run command, then click All Programs > Accessories > Run. Remove the Read Only attribute and set the System attribute. Type the following command: attrib -r +s drive:\<path>\<foldername>


1 Answers

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);
}
like image 126
Mark Avenius Avatar answered Sep 30 '22 02:09

Mark Avenius