Modifying File Attributes

joe_pool_is

Well-known member
Joined
Jan 18, 2004
Messages
451
Location
Texas
Im to a place where I need to modify a files attributes so that I can encrypt or decrypt the file because Hidden or ReadOnly files fail.

Ive written a basic static method (so my threads can call it), and I wanted to post it here for criticism or suggestions:
C#:
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;
  }
}
 
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:

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

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

Lets see why:

Code:
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:
 
Re: Not unsetting ReadOnly or Hidden!

That actually helps a lot.

Thanks for taking the time to write the bits out, Mr. Paul! I hope it comes in handy for others, too.
 
Optimization

Thinking about it, if you plan to use & to unset the ReadOnly and Hidden bits, you dont 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:

C#:
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:
 
Back
Top