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

前端 未结 7 1782
南方客
南方客 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

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

提交回复
热议问题