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

Solution 1:

Answering on your question in title regarding ReadOnly attribute:

FileInfo fileInfo = new FileInfo(pathToAFile);
fileInfo.IsReadOnly = false;

To get control over any attribute yourself you can use File.SetAttributes() method. The link also provides an example.

Solution 2:

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)) 
        {
            File.Create(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);
        } 
        else 
        {
            // 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;
    }
}

Solution 3:

string file = "file.txt";
FileAttributes attrs = File.GetAttributes(file);
if (attrs.HasFlag(FileAttributes.ReadOnly))
    File.SetAttributes(file, attrs & ~FileAttributes.ReadOnly);

Solution 4:

if ((oFileInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
    oFileInfo.Attributes ^= FileAttributes.ReadOnly;

Solution 5:

For a one line solution (provided that the current user has access to change the attributes of the mentioned file) here is how I would do it:

VB.Net

Shell("attrib file.txt -r")

the negative sign means to remove and the r is for read-only. if you want to remove other attributes as well you would do:

Shell("attrib file.txt -r -s -h -a")

That will remove the Read-Only, System-File, Hidden and Archive attributes.

if you want to give back these attributes, here is how:

Shell("attrib file.txt +r +s +h +a")

the order does not matter.

C#

Process.Start("cmd.exe", "attrib file.txt +r +s +h +a");

References

  • Google
  • ComputerHope.com - Lots of examples and OS specific notes
  • Microsoft - Page is for XP, but probably applies to later versions
  • Wikipedia - Particularly the Particularities section