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);
    }
}

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

相关推荐
eggwyw22 分钟前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
布莱克60531 分钟前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
布莱克6051 小时前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包
小七在进步2 小时前
string的实现(3)
开发语言·c++·笔记·visual studio
专注仿真3 小时前
基于 AFSIM 的智能体训练:多智能体强化学习篇 —— QTRAN 算法实战
开发语言·python·算法·php·强化学习·afsim智能体·仿真训练
Funlang5 小时前
RISC-V 上的 Fun:第四套机器码
开发语言·risc-v·龙芯
feixing_fx13 小时前
第一个 JS 程序:在浏览器控制台和 Node 中分别运行
开发语言·前端·javascript·前端框架·ecmascript
Evand J14 小时前
【MATLAB例程】二维IMM-UKF定位,基于四个基站的AOA与测距辅助
开发语言·matlab
feixing_fx14 小时前
变量与声明:let、const、var 的选择边界
开发语言·前端·javascript·前端框架
个 人 练 习 生15 小时前
C++:从零基础到深入了解vector的使用
开发语言·c++·经验分享·学习·程序人生·stl