c# 让文件只读

在C#中,你可以使用以下步骤来使文件变为只读,从而不可修改:

cs 复制代码
using System.IO;

public static void SetFileReadOnly(string filePath)
{
    // 获取文件的当前属性
    FileAttributes attributes = File.GetAttributes(filePath);

    // 如果文件不已经是只读的,则添加只读属性
    if ((attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
    {
        // 添加只读属性并设置回去
        attributes = attributes | FileAttributes.ReadOnly;
        File.SetAttributes(filePath, attributes);
    }
}

这段代码首先获取了指定文件的当前属性,然后检查是否已经设置了只读属性。如果尚未设置,它将添加只读属性,并使用File.SetAttributes方法将更新后的属性设置回文件。

如果你想从只读状态取消只读,可以使用以下代码

cs 复制代码
using System.IO;

public static void RemoveReadOnlyAttribute(string filePath)
{
    // 获取文件的当前属性
    FileAttributes attributes = File.GetAttributes(filePath);

    // 如果文件是只读的,则移除只读属性
    if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
    {
        // 移除只读属性并设置回去
        attributes = attributes & ~FileAttributes.ReadOnly;
        File.SetAttributes(filePath, attributes);
    }
}

这段代码与前面的类似,但这里是移除只读属性而不是添加。请注意,这只会改变文件的系统属性,不会阻止具有足够权限的用户或程序通过其他方式修改文件内容。

相关推荐
2401_894828123 分钟前
从原理到实战:随机森林算法全解析(附 Python 完整代码)
开发语言·python·算法·随机森林
玄同7653 分钟前
Python「焚诀」:吞噬所有语法糖的终极修炼手册
开发语言·数据库·人工智能·python·postgresql·自然语言处理·nlp
羽翼.玫瑰5 分钟前
关于重装Python失败(本质是未彻底卸载Python)的问题解决方案综述
开发语言·python
CRMEB系统商城34 分钟前
CRMEB多商户系统(PHP)- 移动端二开之基本容器组件使用
运维·开发语言·小程序·php
淮北49439 分钟前
科研绘图工具R语言
开发语言·r语言
逍遥德1 小时前
java Map Set List 扩容机制
java·开发语言·list
2501_944521591 小时前
Flutter for OpenHarmony 微动漫App实战:图片加载实现
android·开发语言·前端·javascript·flutter·php
nbsaas-boot1 小时前
基于 Java 21 ScopedValue 的多租户动态数据源完整实践
java·开发语言
liuc03171 小时前
Java项目关于不同key的读取
java·开发语言
Zach_yuan1 小时前
面向对象封装线程:用 C++ 封装 pthread
开发语言·c++·算法