12.6 Making a File Read Only

 <  Day Day Up  >  

You want to change the read-only attribute on a file.


Technique

You can use the SetAttributes method defined in the File class or the Attributes property defined in the FileInfo class to change various attributes of a file, one of which is the read-only attribute. To change just the read-only attribute without affecting any other attributes, use bitwise operators on the current attributes of the file with the attribute you want to change. For instance, to make a file read only, use the logical OR ( ) operator:

 
 File.SetAttributes( fileName, File.GetAttributes(fileName)  FileAttributes.ReadOnly ); 

To remove the read-only attribute from a file, perform a logical AND ( & ) with the current file attributes and the bitwise complement of the FileAttributes.ReadOnly value. The bitwise complement operator is the tilde ( ~ ) character:

 
 File.SetAttributes( fileName, File.GetAttributes(fileName) & (~FileAttributes.ReadOnly) ); 

Comments

The technique just discussed uses a well-known method for manipulating bit fields. The FileAttributes enumerated data type contains values corresponding to a single bit of an integer. In other words, the value 1 corresponds to the value ReadOnly , 2 is for the Hidden attribute, 4 denotes a System file, and so on. If you want to set a certain attribute on a file without affecting any other attributes that are set or cleared, you can simply logically OR the attribute you want to set with the current attribute list. For example, if a file has its hidden attribute set and you also want to set it to read only, you use the code shown earlier. If you look at the values as bits, you see the following:

0 0 1 0 = current attributes

0 0 0 1 = FileAttributes.ReadOnly

0 0 1 1 = current ReadOnly

Note that if the Hidden attribute is cleared to begin with, it remains clear because 0 0 = 0. If you then want to turn the FileAttributes.Hidden value off, you must first take the bitwise complement of the FileAttributes.Hidden value and logically AND ( & ) it with the current attribute list. The bitwise complement is the result of changing any 1s to 0s and any 0s to 1s:

0 0 1 1 = current attributes

1 1 0 1 = bitwise complement of FileAttribute.Hidden

0 0 0 1 = current and Hidden complement

Although you can use this technique with many other enumerated data types within the .NET framework, you must ensure that the values in the enumeration follow a bit-flag pattern. If the values are anything other than a 2 n domain you have to utilize a different method.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net