Read file and directory attributes
I’ve just finished a small application that does some IO work on files and directories. The application moves directories to new locations, but every time a folder or file was marked read-only it would of course throw an exception. The same happened with system files and folders. The obvious solution would be to add a try/catch block to the method, but I wanted something better.
I came up with a method that checks a file or directory’s access, so that I wouldn’t try to delete a read-only, hidden system file or any combination of that.
/// <summary>
/// Checks
if a directory or file is system-, hidden- or readonly.
/// </summary>
private static bool IsAttributesAllowed(FileAttributes attributes)
{
if ((attributes
& FileAttributes.Hidden)
== FileAttributes.Hidden)
return false;
if ((attributes
& FileAttributes.System)
== FileAttributes.System)
return false;
if ((attributes
& FileAttributes.ReadOnly)
== FileAttributes.ReadOnly)
return false;
return true;
}
That method allows me to write the following code:
>
FileInfo file
= new FileInfo(filename);
if (IsAttributesAllowed(file.Attributes))
{
DoSomething();
}
Or with directories:
>
DirectoryInfo dir
= new DirectoryInfo(foldername);
if (IsAttributesAllowed(dir.Attributes))
{
DoSomething();
}
The application hasn’t thrown any exceptions using this method, but it is always a good idea to be safe when dealing with IO.
>