首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从文件中删除单个属性(例如ReadOnly)?

如何从文件中删除单个属性(例如ReadOnly)?
EN

Stack Overflow用户
提问于 2011-09-13 17:29:18
回答 8查看 95.4K关注 0票数 88

假设一个文件有以下属性:ReadOnly, Hidden, Archived, System如何只删除一个属性?(例如ReadOnly)

如果我使用以下命令,它将删除所有属性:

代码语言:javascript
复制
IO.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-09-13 17:33:00

MSDN:您可以像这样删除任何属性

(但是@sll对ReadOnly的回答更适合于这个属性)

代码语言:javascript
复制
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;
    }
}
票数 113
EN

Stack Overflow用户

发布于 2011-09-13 17:32:59

回答标题中有关ReadOnly属性的问题:

代码语言:javascript
复制
FileInfo fileInfo = new FileInfo(pathToAFile);
fileInfo.IsReadOnly = false;

要自己控制任何属性,可以使用File.SetAttributes()方法。该链接还提供了一个示例。

票数 136
EN

Stack Overflow用户

发布于 2011-09-13 17:38:03

代码语言:javascript
复制
string file = "file.txt";
FileAttributes attrs = File.GetAttributes(file);
if (attrs.HasFlag(FileAttributes.ReadOnly))
    File.SetAttributes(file, attrs & ~FileAttributes.ReadOnly);
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7399611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档