I have a file on disk. I want to check if its readonly. If yes, I want to make it writeable. Make modifications and save it. And change it back to readonly. To do this I am trying to execute the below code in c#. It removes the readonly attribute and let me write and save modifications. However, it fails to set it back to readonly.
Appreciate your help.
public class Test
{
public static void Main(string[] args)
{
//This is a readonly file
string path = @"c:\temp\MyTest.txt";
FileAttributes initialattributes = File.GetAttributes(modelFilename);
if ((initialattributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
//Removing the readonly attribute
initialattributes = RemoveAttribute(initialattributes, FileAttributes.ReadOnly);
File.SetAttributes(path, initialattributes);
//Performing some write operation and saving file
//Trying to set the attribute back to readonly but its not working
File.SetAttributes(path, File.GetAttributes(modelFilename) | FileAttributes.ReadOnly);
}
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
}