C# make file read/write from readonly
Asked Answered
D

3

32

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

Disarray answered 10/11, 2011 at 14:41 Comment(0)
C
56

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.

Christology answered 10/11, 2011 at 14:48 Comment(4)
I'm guessing ~ reverses the attribute?Disarray
Pretty much - the ~ operator returns a bitwise complement of a given value. Semantically, what the above says is, "Set the attributes of file myfile.txt to the attributes of myfile.txt except for the ReadOnly attribute."Christology
If instantiating a FileInfo object on your file is an option for you, you can then simply set its IsReadOnly property. msdn.microsoft.com/en-us/library/system.io.fileinfo.aspxParamount
And if you want to make the file ReadOnly (or assign any other attribute), you need to use | instead of &. For example: File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);Carry
B
21

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);
Backlog answered 10/11, 2011 at 14:50 Comment(0)
C
3

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;
        }
    }
Combs answered 19/7, 2018 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.