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

Mil*_*ike 79 .net c# file file-attributes

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

如果我使用:

Io.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
Run Code Online (Sandbox Code Playgroud)

它删除所有属性.

sll*_*sll 123

在关于ReadOnly属性的标题中回答您的问题:

FileInfo fileInfo = new FileInfo(pathToAFile);
fileInfo.IsReadOnly = false;
Run Code Online (Sandbox Code Playgroud)

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

  • 作为一个单行:新的FileInfo(fileName){IsReadOnly = false} .Refresh() (3认同)
  • 是否需要Refresh()?[MSDN上的这个例子](http://msdn.microsoft.com/en-us/library/system.io.fileinfo.isreadonly(v = vs.110).aspx)表明它不是,和我的代码(如果我不打电话的话,我认真地使用Mono. (2认同)

Pre*_*gha 104

来自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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Rub*_*ias 13

string file = "file.txt";
FileAttributes attrs = File.GetAttributes(file);
if (attrs.HasFlag(FileAttributes.ReadOnly))
    File.SetAttributes(file, attrs & ~FileAttributes.ReadOnly);
Run Code Online (Sandbox Code Playgroud)