Удалить один атрибут (скажем, "только для чтения") у файла?

Предположим, у файла есть следующие атрибуты: ReadOnly, Hidden, Archived, System.

Как я могу снять только один из них, скажем ReadOnly?

Если я использую следующий код, он снимает ВСЕ атрибуты:

IO.File.SetAttributes("File.txt",IO.FileAttributes.Normal)

Свободный перевод вопроса How to remove a single Attribute (e.g. ReadOnly) from a File? от участника @MilMike.


Ответы (1 шт):

Автор решения: A K

Если говорить именно ReadOnly то его проще всего снять следующим кодом:

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

В общем случае код для манипулирования одним конкретным атрибутом выглядит примерно следующим образом (см. MSDN):

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;
    }
}

Использованы свободные переводы ответов How to remove a single Attribute (e.g. ReadOnly) from a File? от участника @sll и How to remove a single Attribute (e.g. ReadOnly) from a File? от участника @Preet Sangha.

Update Дополнительно рекомендую почитать по теме битовых операций вот эти вопросы на ru so:

→ Ссылка