Подтвердить что ты не робот

Как удалить один атрибут (например, ReadOnly) из файла?

Скажем, файл имеет следующие атрибуты: ReadOnly, Hidden, Archived, System. Как удалить только один атрибут? (например, ReadOnly)

Если я использую:

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

он удаляет все атрибуты.

4b9b3361

Ответ 1

Из MSDN: вы можете удалить любой атрибут, подобный этому

(но ответ @sll для просто ReadOnly лучше всего подходит именно для этого атрибута)

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

Ответ 2

Отвечая на ваш вопрос в заголовке относительно атрибута ReadOnly:

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

Чтобы получить контроль над любым атрибутом, вы можете использовать метод File.SetAttributes(). Ссылка также дает пример.

Ответ 3

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

Ответ 4

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

Ответ 5

Для решения одной строки (при условии, что у текущего пользователя есть доступ к изменению атрибутов упомянутого файла), вот как я это сделаю:

VB.Net

Shell("attrib file.txt -r")

отрицательный знак означает remove, а r - только для чтения. если вы хотите также удалить другие атрибуты, выполните следующие действия:

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

Это приведет к удалению атрибутов Read-Only, System-File, Hidden и Archive.

если вы хотите вернуть эти атрибуты, вот как:

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

порядок не имеет значения.

С#

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

Ссылки

Ответ 6

/// <summary>
/// Addes the given FileAttributes to the given File.
/// It possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
/// </summary>
public static void AttributesSet(this FileInfo pFile, FileAttributes pAttributes)
{
    pFile.Attributes = pFile.Attributes | pAttributes;
    pFile.Refresh();
}

/// <summary>
/// Removes the given FileAttributes from the given File.
/// It possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
/// </summary>
public static void AttributesRemove(this FileInfo pFile, FileAttributes pAttributes)
{
    pFile.Attributes = pFile.Attributes & ~pAttributes;
    pFile.Refresh();
}

/// <summary>
/// Checks the given File on the given Attributes.
/// It possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
/// </summary>
/// <returns>True if any Attribute is set, False if non is set</returns>
public static bool AttributesIsAnySet(this FileInfo pFile, FileAttributes pAttributes)
{
    return ((pFile.Attributes & pAttributes) > 0);
}

/// <summary>
/// Checks the given File on the given Attributes.
/// It possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
/// </summary>
/// <returns>True if all Attributes are set, False if any is not set</returns>
public static bool AttributesIsSet(this FileInfo pFile, FileAttributes pAttributes)
{
    return (pAttributes == (pFile.Attributes & pAttributes));
}

Пример:

private static void Test()
{
    var lFileInfo = new FileInfo(@"C:\Neues Textdokument.txt");
    lFileInfo.AttributesSet(FileAttributes.Hidden | FileAttributes.ReadOnly);
    lFileInfo.AttributesSet(FileAttributes.Temporary);
    var lBool1 = lFileInfo.AttributesIsSet(FileAttributes.Hidden);
    var lBool2 = lFileInfo.AttributesIsSet(FileAttributes.Temporary);
    var lBool3 = lFileInfo.AttributesIsSet(FileAttributes.Encrypted);
    var lBool4 = lFileInfo.AttributesIsSet(FileAttributes.ReadOnly | FileAttributes.Temporary);
    var lBool5 = lFileInfo.AttributesIsSet(FileAttributes.ReadOnly | FileAttributes.Encrypted);
    var lBool6 = lFileInfo.AttributesIsAnySet(FileAttributes.ReadOnly | FileAttributes.Temporary);
    var lBool7 = lFileInfo.AttributesIsAnySet(FileAttributes.ReadOnly | FileAttributes.Encrypted);
    var lBool8 = lFileInfo.AttributesIsAnySet(FileAttributes.Encrypted);
    lFileInfo.AttributesRemove(FileAttributes.Temporary);
    lFileInfo.AttributesRemove(FileAttributes.Hidden | FileAttributes.ReadOnly);
}