Remove readonly attribute from directory

余生颓废 提交于 2019-11-26 13:09:23

问题


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


回答1:


var di = new DirectoryInfo("SomeFolder");
di.Attributes &= ~FileAttributes.ReadOnly;



回答2:


Here's a good link to examples of modifying file attributes using c#

http://www.csharp-examples.net/file-attributes/

based on their example, you can remove the Read Only attribute like this (I haven't tested this):

File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);



回答3:


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 reset ReadOnly flag.

Use " |= FileAttributes.ReadOnly;" to set ReadOnly flag.




回答4:


If you're attempting to remove the attribute of a file in the file system, create an instance of the System.IO.FileInfo class and set the property IsReadOnly to false.

        FileInfo file = new FileInfo("c:\\microsoft.text");
        file.IsReadOnly = false;



回答5:


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



回答6:


Setting Attributes to FileAttributes.Normal worked for me on both folders and files.




回答7:


    public static void DeleteDirectory(string path)
    {
        var directory = new DirectoryInfo(path) 
        { Attributes =FileAttributes.Normal };
        foreach (var info in directory.GetFileSystemInfos("*", SearchOption.AllDirectories))
        {
            info.Attributes = FileAttributes.Normal;
        }
        directory.Delete(true);
    }


来源:https://stackoverflow.com/questions/2316308/remove-readonly-attribute-from-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!