Following example demonstrates how to get or set file attributes; how to add attributes and how to remove attributes from current ones.
Get file attributes
We can get file attributes by using static method File.GetAttriĀbutes. This method returns FileAttributes which is bitwise combination of the file attribute flags.
string myfilePath = @"c:\sample.txt"; FileAttributes attributes = File.GetAttributes(myfilePath); |
Set file attributes
We can set file attributes by using static method File.SetAttriĀbutes. Parameter of the method is a bitwise combination of FileAttributes enumeration.
File.SetAttributes(myfilePath, FileAttributes.Normal); File.SetAttributes(myfilePath, FileAttributes.Archive | FileAttributes.ReadOnly); |
Example showing how we can check for file attributes
First we can check whether file has any attribute or not and get current attributes then we can apply bitwise AND (&) operator with other attributes.
bool isReadOnly = ((File.GetAttributes(myfilePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly); bool isHidden = ((File.GetAttributes(myfilePath) & FileAttributes.Hidden) == FileAttributes.Hidden); bool isArchive = ((File.GetAttributes(myfilePath) & FileAttributes.Archive) == FileAttributes.Archive); bool isSystem = ((File.GetAttributes(myfilePath) & FileAttributes.System) == FileAttributes.System); |
Example showing how we can add attributes to file
First we can get current attributes of file then we can use bitwise OR (|) with other attributes.
File.SetAttributes(myfilePath, File.GetAttributes(myfilePath) | FileAttributes.Hidden); File.SetAttributes(myfilePath, File.GetAttributes(myfilePath) | (FileAttributes.Archive | FileAttributes.ReadOnly)); |
Example showing how we can Clear/Delete file attributes
First we can get current attributes of file then we can use the operator (AND (&)) with a mask.
File.SetAttributes(myfilePath, File.GetAttributes(myfilePath) & ~FileAttributes.Hidden); File.SetAttributes(myfilePath, File.GetAttributes(myfilePath) & ~(FileAttributes.Archive | FileAttributes.ReadOnly)); |

Leave a Reply
You must be logged in to post a comment.