如何从文件中删除单个属性(例如只读)? [英] How to remove a single Attribute (e.g. ReadOnly) from a File?
本文介绍了如何从文件中删除单个属性(例如只读)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设文件具有以下属性:ReadOnly、Hidden、Archived、System
.如何只删除一个属性?(例如 ReadOnly)
Let say, a file has the following attributes: ReadOnly, Hidden, Archived, System
.
How can I remove only one Attribute? (for example ReadOnly)
如果我使用以下内容,它会删除所有属性:
If I use the following, it removes all the attributes:
IO.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
推荐答案
来自 MSDN:您可以删除这样的任何属性
From MSDN: You can remove any attribute like this
(但@sll 对只读的回答更适合该属性)
(but @sll's answer for just ReadOnly is better for just that attribute)
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c: empMyTest.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;
}
}
这篇关于如何从文件中删除单个属性(例如只读)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文