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

前端 未结 7 1785
南方客
南方客 2020-11-28 08:54

Let say, a file has the following attributes: ReadOnly, Hidden, Archived, System. How can I remove only one Attribute? (for example ReadOnly)

7条回答
  •  一个人的身影
    2020-11-28 09:27

    /// 
    /// Addes the given FileAttributes to the given File.
    /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
    /// 
    public static void AttributesSet(this FileInfo pFile, FileAttributes pAttributes)
    {
        pFile.Attributes = pFile.Attributes | pAttributes;
        pFile.Refresh();
    }
    
    /// 
    /// Removes the given FileAttributes from the given File.
    /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
    /// 
    public static void AttributesRemove(this FileInfo pFile, FileAttributes pAttributes)
    {
        pFile.Attributes = pFile.Attributes & ~pAttributes;
        pFile.Refresh();
    }
    
    /// 
    /// Checks the given File on the given Attributes.
    /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
    /// 
    /// True if any Attribute is set, False if non is set
    public static bool AttributesIsAnySet(this FileInfo pFile, FileAttributes pAttributes)
    {
        return ((pFile.Attributes & pAttributes) > 0);
    }
    
    /// 
    /// Checks the given File on the given Attributes.
    /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly
    /// 
    /// True if all Attributes are set, False if any is not set
    public static bool AttributesIsSet(this FileInfo pFile, FileAttributes pAttributes)
    {
        return (pAttributes == (pFile.Attributes & pAttributes));
    }
    

    Example:

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

提交回复
热议问题