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" );
elseConsole.WriteLine( "Nope" );

Changing File Permissions
lukeliu
Kajal Sinha
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
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:
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:
and
So, when you are removing some attribute you must be sure, that the attribute is set before you can remove it.
Markku