Remove readonly attribute from directory

前端 未结 8 951
情歌与酒
情歌与酒 2020-12-01 06:23

How can I programatically remove the readonly attribute from a directory in C#?

相关标签:
8条回答
  • 2020-12-01 06:57

    Using the -= assignment operator is dangerous for two reasons:
    1) It works ONLY IF the ReadOnly attribute is set, thus a test is required beforehand.
    2) It is performing a subtract operation, which is not is not the best choice when working with binary flags. The subtract operation works if condition 1 (above) is true, but additional subtract operations will ALTER OTHER BITS in the FileAttributes field!

    Use &= ~FileAttributes.ReadOnly; to remove ReadOnly flag.

    Use |= FileAttributes.ReadOnly; to apply ReadOnly flag.

    0 讨论(0)
  • 2020-12-01 06:59

    Got it finally. ;)

    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo("c:\\test");
    
            FileAttributes f = di.Attributes;
    
            Console.WriteLine("Directory c:\\test has attributes:");
            DecipherAttributes(f);
    
        }
    
        public static void DecipherAttributes(FileAttributes f)
        {
            // To set use File.SetAttributes
    
            File.SetAttributes(@"C:\test", FileAttributes.ReadOnly);
    
            if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                Console.WriteLine("ReadOnly");
    
            // To remove readonly use "-="
            f -= FileAttributes.ReadOnly;
    
            if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                Console.WriteLine("ReadOnly");
            else
                Console.WriteLine("Not ReadOnly");
        }
    }
    
    0 讨论(0)
提交回复
热议问题