【发布时间】:2019-02-09 06:35:22
【问题描述】:
我在磁盘上有一个文件。我想检查它是否是只读的。如果是,我想让它可写。进行修改并保存。并将其改回只读。 为此,我尝试在 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;
}
}
【问题讨论】:
-
应该可以。在尝试将其属性更改回来之前,您确定要关闭文件吗?
-
那个“重复的问题”与 OP 使用的代码相同。这不是一个重复的问题 - OP 不想知道 如何 这样做; OP 想知道为什么表面上正确的方法不起作用。
标签: c# setattribute