Read file and directory attributes

Sep 10, 2006

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.

>* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (2) -

 Eber Irigoyen
Eber Irigoyen
9/10/2006 9:52:22 PM #

private static bool IsAttributesAllowed(FileAttributes attributes) {
    return (attributes & (FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReadOnly)) == 0;
}

 Mads Kristensen
Mads Kristensen
9/11/2006 6:12:02 AM #

Eber: Much cleaner and better. Thank you

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.