比方说,一个文件有以下属性: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;
    }
}

.net相关问答推荐

从Couchbase删除_txn文档的推荐方法?""

从删除项目时重新索引的列表中删除项目的最佳算法是什么?

NET 6:控制器方法不可访问

部署时如何控制红隼端口?

将 DataRowCollection 转换为 IEnumerable

异步总是 WaitingForActivation

共享 AssemblyInfo 用于跨解决方案的统一版本控制

.NET 中工作线程和 I/O 线程的简单描述

无法将文件 *.mdf 作为数据库附加

Await 运算符只能在 Async 方法中使用

Dapper 是否支持 SQL 2008 表值参数?

关闭 Visual Studio 中所有选项卡但当前选项卡的键盘快捷键?

没有 @Html.Button !

如何使我的托管 NuGet 包支持 C++/CLI 项目?

从流中获取 TextReader?

如何获取命名空间中的所有类?

如何重新启动 WPF 应用程序?

使用 C# vs F# 或 F# vs C# 有什么好处?

WinForms 中的模型视图演示者

在构建事件命令行中放置注释的正确方法?