比方说,一个文件有以下属性:ReadOnly, Hidden, Archived, System
.
How can I remove only one Attribute?(例如只读)
如果我使用以下选项,它会删除所有属性:
IO.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
比方说,一个文件有以下属性:ReadOnly, Hidden, Archived, System
.
How can I remove only one Attribute?(例如只读)
如果我使用以下选项,它会删除所有属性:
IO.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
从MSDN开始:你可以删除任何这样的属性
(但是@sll对just ReadOnly的回答更适合该属性)
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// Create the file if it exists.
if (!File.Exists(path))
{
File.Create(path);
}
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(path, attributes);
Console.WriteLine("The {0} file is no longer RO.", path);
}
else
{
// Make the file RO
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
Console.WriteLine("The {0} file is now RO.", path);
}
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
}