如何从文件中删除一个属性(如只读)? [英] How to remove a single Attribute (e.g. ReadOnly) from a File?

查看:433
本文介绍了如何从文件中删除一个属性(如只读)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让说,文件具有以下属性:只读,隐藏,存档,系统。 如何删除只有一个属性?(例如只读) 如果我使用:

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:

Io.File.SetAttributes("File.txt",IO.FileAttributes.Normal)

它会删除所有属性。

it removes all the attributes.

推荐答案

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:\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;
    }
}

这篇关于如何从文件中删除一个属性(如只读)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆