Saturday, May 30, 2009

Set a file as read-only

// Set the read-only attribute of a file to true or false

//
// Set the attribute read only of a file
//

// Full path of file
// If true, the file will be set readonly. Else will be set writable

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);
}
}

No comments:

Post a Comment