blackhatmario blackhatmario - 1 year ago 109
C# Question

How to remove a single Attribute (e.g. ReadOnly) from a File?

Let say, a file has the following attributes:

ReadOnly, Hidden, Archived, System
How can I remove only one Attribute? (for example ReadOnly)

If I use:


it removes all the attributes.

Answer Source

From MSDN: You can remove any attribute like this

(but @sll's answer for just ReadOnly is better for just that attribute)

using System;
using System.IO;
using System.Text;
class Test 
    public static void Main() 
        string path = @"c:\temp\MyTest.txt";

        // Create the file if it exists.
        if (!File.Exists(path)) 

        FileAttributes attributes = File.GetAttributes(path);

        if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            // Make the file RW
            attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
            File.SetAttributes(path, attributes);
            Console.WriteLine("The {0} file is no longer RO.", path);
            // Make the file RO
            File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
            Console.WriteLine("The {0} file is now RO.", path);

    private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
        return attributes & ~attributesToRemove;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download