joe_pool_is Posted December 12, 2008 Posted December 12, 2008 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; } } Quote Avoid Sears Home Improvement
MrPaul Posted December 15, 2008 Posted December 15, 2008 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: Quote Never trouble another for what you can do for yourself.
joe_pool_is Posted December 15, 2008 Author Posted December 15, 2008 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. Quote Avoid Sears Home Improvement
MrPaul Posted December 15, 2008 Posted December 15, 2008 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: Quote Never trouble another for what you can do for yourself.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.