假设一个文件有以下属性:ReadOnly, Hidden, Archived, System
。如何只删除一个属性?(例如ReadOnly)
如果我使用以下命令,它将删除所有属性:
IO.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
发布于 2011-09-13 17:33:00
从MSDN:您可以像这样删除任何属性
(但是@sll对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;
}
}
发布于 2011-09-13 17:32:59
回答标题中有关ReadOnly
属性的问题:
FileInfo fileInfo = new FileInfo(pathToAFile);
fileInfo.IsReadOnly = false;
要自己控制任何属性,可以使用File.SetAttributes()
方法。该链接还提供了一个示例。
发布于 2011-09-13 17:38:03
string file = "file.txt";
FileAttributes attrs = File.GetAttributes(file);
if (attrs.HasFlag(FileAttributes.ReadOnly))
File.SetAttributes(file, attrs & ~FileAttributes.ReadOnly);
https://stackoverflow.com/questions/7399611
复制相似问题