File Attributes code samples in C#

In this article, learn how to read various file attributes from any directory or file using C# with code samples.


File Attributes code samples in C#

In C#, the enum FileAttributes provides the attributes for files and directories. The FileAttribute enum is defined in System.IO namespace of System.Runtime.dll assembly.

Function to check whether path is FILE or DIRECTORY:

/// 
/// Function to check whether path is FILE or DIRECTORY 
/// 
/// 
/// 
public static bool IsDirectory(string sDirectoryOrFilePath)
   {
       try
       {
           FileAttributes attr = File.GetAttributes(sDirectoryOrFilePath);
                
           if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
           {
               //Its Directory
               return false;
           }

           //Its File
           return true;
       }
       catch (DirectoryNotFoundException ex)
       {
           throw ex;
       }
       catch (FileNotFoundException ex)
       {
           throw ex;
       }  
}

Function to check whether the FILE or DIRECTORY is hidden or not:

/// 
/// Function to check whether the FILE or DIRECTORY is hidden or not.
/// 
/// 
/// 
public static bool IsHiddenFile(string sDirectoryOrFilePath)
{
     try
     {
          FileAttributes attr = File.GetAttributes(sDirectoryOrFilePath);

          if ((attr & FileAttributes.Hidden) == FileAttributes.Hidden)
          {
               //Its Hidden file
               return true;
          }

          //Its Archive file.
          return false;
      }
      catch (DirectoryNotFoundException ex)
      {
          throw ex;
      }
      catch (FileNotFoundException ex)
      {
          throw ex;
      }
}

Function to check whether the FILE or DIRECTORY is hidden or not.

/// 
/// Function to check whether the FILE or DIRECTORY is readonly or not.
/// 
/// 
/// 
public static bool IsReadOnlyFile(string sDirectoryOrFilePath)
{
    try
    {
        FileAttributes attr = File.GetAttributes(sDirectoryOrFilePath);
                
        if ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
        {
            //Its ReadOnly file
            return true;
        }

        //Its Archive file.
        return false;
    }
    catch (DirectoryNotFoundException ex)
    {
        throw ex;
    }
    catch (FileNotFoundException ex)
    {
        throw ex;
    }
}

– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Creating EventLog in C# | Windows EventViewer
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo