Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# make file read/write from readonly

If File.SetAttributes("C:\\myFile.txt", FileAttributes.ReadOnly); sets a file as read only, how do I set it back to read/write if I need to?

I suspect it would be FileAttributes.Normal however will this change any other properties of the file? There isn't an awfully descriptive note on the MSDN site...

The file is normal and has no other attributes set. This attribute is valid only if used alone.

Thanks

like image 250
Thomas Clayson Avatar asked Nov 10 '11 14:11

Thomas Clayson


3 Answers

To remove just the ReadOnly attribute, you'd do something like this:

File.SetAttributes("C:\\myfile.txt", File.GetAttributes("C:\\myfile.txt") & ~FileAttributes.ReadOnly);

This will remove the ReadOnly attribute, but preserve any other attributes that already exist on the file.

like image 159
matt Avatar answered Oct 15 '22 07:10

matt


File.SetAttributes replaces ALL attributes on the file.

The proper way to set and remove attributes is to first get the attributes, apply changes, and set them.

e.g.

var attr = File.GetAttributes(path);

// set read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(path, attr);

// unset read-only
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
like image 29
Joe Avatar answered Oct 15 '22 05:10

Joe


I understand this is very late, but I wanted to share my solution hoping it helps others. I needed something similar and the way I accomplished was by setting the IsReadOnly property on FileInfo.

    private void UnsetReadOnlyAttribute(string filePathWithName)
    {
        FileInfo fileInfo = new FileInfo(filePathWithName);
        if (fileInfo.IsReadOnly)
        {
            fileInfo.IsReadOnly = false;
        }
    }
like image 35
anish Avatar answered Oct 15 '22 06:10

anish