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



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



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



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


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

575   7  

7 ответов:

С MSDN: вы можете удалить любой атрибут такой

(но ответ @sll для just 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;
    }
}

отвечая на ваш вопрос в заголовке о :

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

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

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

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

VB.Net

Shell("attrib file.txt -r")

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

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

это приведет к удалению атрибутов только для чтения, системного файла, скрытых и архивных.

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

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

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

C#

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

ссылки

/// <summary>
/// Addes the given FileAttributes to the given File.
/// It's 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's 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's 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's 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);
}

используйте этот:

private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)

Подробнее читайте здесь в MSDN:http://msdn.microsoft.com/en-us/library/system.io.file.setattributes.aspx

Comments

    Ничего не найдено.