Changing File Permissions

I have a file that I want to copy to a different location. Sometimes the files will be marked as ReadOnly. I want to change the permission to not read only and then copy the file and change the permission back. Is there any way to handle this

Here is how I detect the attribute:

string file = @"C:\File.jpg";

FileInfo info = new FileInfo( file );

if( (info.Attributes & FileAttributes.ReadOnly) != 0 )

Console.WriteLine( "Read Only" );

else

Console.WriteLine( "Nope" );



Answer this question

Changing File Permissions

  • lukeliu

    I don't have .IsReadOnly as a method. Is this a .NET 2.0 change
  • Kajal Sinha

    Sorry. It is.

    But you can make it like this:

    info.Attributes = info.Attributes | FileAttributes.ReadOnly; // ReadOnly
    info.Attributes = (
    info.Attributes | FileAttributes.ReadOnly) ^ FileAttributes.ReadOnly; // not ReadOnly

    Markku

  • Syed Junaid

    Something like this:

    FileInfo sourceInfo = new FileInfo("source.name");
    Boolean readOnly = sourceInfo.IsReadOnly;
    sourceInfo.IsReadOnly = false;
    FileInfo targetInfo = sourceInfo.CopyTo("target.name");
    tagetInfo.IsReadOnly = readOnly;

    but you can copy (or move) file to other location even if it's ReadOnly. So you can do like this:

    FileInfo info = new FileInfo("source.name");
    info.CopyTo("target.name");


  • *ferhat

    Little explain.

    If you don't care other atributes (Hidden, Archve etc.) you can simply make this:

    info.Attributes = FileAttributes.Normal;

    info.Attributes = FileAttributes.ReadOnly;

    But if you don't want to change other attributes you must do bitwise operations and

    here little explain:

    | (or) make this 101 | 010 = 111 or this 111 | 010 = 111

    and

    ^ (xor) make this 111 ^ 010 = 101

    So, when you are removing some attribute you must be sure, that the attribute is set before you can remove it.

    Markku


  • Changing File Permissions