Wednesday, November 10, 2010

Tip: How to remove read-only attribute of a file?

Below are the helper methods used to set or remove read-only attribute of a file. As well as I've provided a method to check the read-only attribute of a file.

       /// <summary>
       /// Sets the passed file as readonly.
       /// </summary>
       /// <param name="filePath">The fully qualified name of a file, or the relative file name.</param>
       public static void SetReadOnly(string filePath)
       {
          SetReadOnly(filePath, true);
       }

       /// <summary>
       /// Sets the passed file to either readonly or not.
       /// </summary>
       /// <param name="filePath">The fully qualified name of a file, or the relative file name.</param>
       /// <param name="readOnly">true to make the file as readonly; otherwise, false.</param>
       public static void SetReadOnly(string filePath, bool readOnly)
       {
          if (String.IsNullOrEmpty(filePath))
              throw new ArgumentNullException("FilePath");

          if (!File.Exists(filePath)) return;
          FileInfo myFile = new FileInfo(filePath);
          myFile.IsReadOnly = readOnly;
       }

       /// <summary>
       /// Gets a value that determines if the passed file is read only.
       /// </summary>
       /// <param name="filePath">The fully qualified name of a file, or the relative file name.</param>
       /// <returns>true if the current file is read only; otherwise, false.</returns>
       public static bool IsReadOnly(string filePath)
       {
          if (String.IsNullOrEmpty(filePath))
              throw new ArgumentNullException("FilePath");

          if (!File.Exists(filePath))
              throw new ArgumentException(String.Format("'{0}' file not exists.", filePath));

          FileInfo myFile = new FileInfo(filePath);
          return myFile.IsReadOnly;
       }

No comments:

Post a Comment