Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I'm to a place where I need to modify a file's attributes so that I can encrypt or decrypt the file because Hidden or ReadOnly files fail.

 

I've written a basic static method (so my threads can call it), and I wanted to post it here for criticism or suggestions:

static bool FileExists(string file) {
 if (File.Exists(file) == true) {
   FileInfo fi = new FileInfo(file);
   if ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
     return false;
   }
   if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) {
     fi.Attributes &= FileAttributes.ReadOnly; // & removes, | adds
     // or, toggle the ReadOnly portion only (use one or the other, but not both)
     // fi.Attributes ^= FileAttributes.ReadOnly;
   }
   if ((fi.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden){
     fi.Attributes &= FileAttributes.Hidden;
   }
   return true;
 } else {
   return false;
 }
}

Posted

Not unsetting ReadOnly or Hidden!

 

The & operator does not unset bits. It can be used to unset a bits, but first you need to invert (not) the bitmask:

 

//This makes it so that ONLY ReadOnly is set:
fi.Attributes &= FileAttributes.ReadOnly;

//This unsets ReadOnly:
fi.Attributes &= ~FileAttributes.ReadOnly;

 

Lets see why:

 

fi.Attributes: 00100001 (Archive and ReadOnly)
ReadOnly     : 00000001
& of above   : 00000001 (just ReadOnly)

fi.Attributes: 00100001 (Archive and ReadOnly)
~ReadOnly    : 11111110
& of above   : 00100000 (just Archive)

 

Good luck :cool:

Never trouble another for what you can do for yourself.
Posted

Optimization

 

Thinking about it, if you plan to use & to unset the ReadOnly and Hidden bits, you don't really need to be doing the comparison, as the operation will have no effect if the bits are not set. This means your code can be simplified to:

 

static bool FileExists(string file) {
 if (File.Exists(file)) {
   FileInfo fi = new FileInfo(file);
   if ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
     return false;
   }
   //Always unset ReadOnly bit
   fi.Attributes &= ~FileAttributes.ReadOnly;
   //Always unset Hidden bit
   fi.Attributes &= ~FileAttributes.Hidden;
   return true;
 } else {
   return false;
 }
}

 

Good luck :cool:

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...