在 C# 中将文件的文件属性设置为只读

Set file attributes on a file to readonly in c#

我在磁盘上有一个文件。我想检查它是否只读。如果是,我想让它可写。进行修改并保存。并将其改回只读。 为此,我尝试在 C# 中执行以下代码。它删除了只读属性,让我编写并保存修改。但是,它无法将其设置回只读。

感谢您的帮助。


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

}

这只是一个猜测,但您的问题很可能是因为您在不同的文件上设置和获取属性。即 pathmodelFilename

File.SetAttributes(path, File.GetAttributes(modelFilename) | FileAttributes.ReadOnly);

为什么这些名字不同?为什么不试试

File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);

甚至只是作为测试

File.SetAttributes(path,  FileAttributes.ReadOnly);

虽然在阅读您的代码时,不清楚您在使用 modelFilenameinitialattributes 做什么,为什么它与 path 不同,以及为什么您不能直接调用

File.SetAttributes(path, initialattributes);

此外,是的,请确保文件句柄已如评论中所述关闭,这可能会破坏交易(未知)