Scott
Scott

Reputation:

How do I change the Read-only file attribute for each file in a folder using c#?

How do I change the Read-only file attribute for each file in a folder using c#?

Thanks

Upvotes: 9

Views: 11753

Answers (4)

Mike
Mike

Reputation: 937

If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:

Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);

Upvotes: 1

mathieu
mathieu

Reputation: 31202

You can try this : iterate on each file and subdirectory :

public void Recurse(DirectoryInfo directory)
{
    foreach (FileInfo fi in directory.GetFiles())
    {
        fi.IsReadOnly = false; // or true
    }

    foreach (DirectoryInfo subdir in directory.GetDirectories())
    {
        Recurse(subdir);
    }
}

Upvotes: 9

Tom Ritter
Tom Ritter

Reputation: 101340

Use File.SetAttributes in a loop iterating over Directory.GetFiles

Upvotes: 2

Jeffrey L Whitledge
Jeffrey L Whitledge

Reputation: 59463

foreach (string fileName in System.IO.Directory.GetFiles(path))
{
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

    fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
    // or
    fileInfo.IsReadOnly = true;
}

Upvotes: 13

Related Questions