Set a file as read-only





8
Date Submitted Thu. Aug. 24th, 2006 8:31 AM
Revision 1 of 1
Helper axsaxs
Tags Attribute | CSharp | read-only
Comments 0 comments
Set the read-only attribute of a file to true or false.

/// <summary>
/// Set the attribute read only of a file
/// </summary>
/// <param name="fullName">Full path of file</param>
/// <param name="readOnly">If true, the file will be set readonly. Else will be set writable</param>
public void SetReadOnly(string fullName, bool readOnly)
{
        FileInfo filePath = new FileInfo(fullName);
        try
        {

                if (filePath.Exists)
                {
                        FileAttributes attr;
                        if (readOnly)
                        {
                                attr = (FileAttributes)
                                (filePath.Attributes | FileAttributes.ReadOnly);
                        }
                        else
                        {
                                attr = (FileAttributes)
                                (filePath.Attributes - FileAttributes.ReadOnly);
                        }
                        File.SetAttributes(filePath.FullName, attr);
                }

        }
        catch (IOException e)
        {
                System.Diagnostics.Debug.WriteLine(e.Source);
                System.Diagnostics.Debug.WriteLine(e.Message);
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
        }
}
 

Alessio Saltarin

axsaxs.altervista.org

Comments

There are currently no comments for this snippet.

Voting