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

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

相关推荐
君顾12 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
香菜TTT3 小时前
大模型上下文协议(MCP):AI 应用的“USB-C”接口技术
开发语言·人工智能·经验分享
aramae3 小时前
模拟实现strlen()函数 (C语言)
c语言·开发语言·后端
Neil20134 小时前
ajax跨域请求
c#
唐青枫4 小时前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net
jimy14 小时前
readelf 查看“派生类”的vtable符号
开发语言·c++
ctlover5 小时前
排序与查找算法详解
开发语言·python
YYYing.5 小时前
【C++进阶系列 (七)】C++ RTTI 深度剖析:从 typeid 到 dynamic_cast 的底层之旅
开发语言·c++·c/c++·rtti
nvvas6 小时前
Java 入门(四):数组——数据的集合管理
java·开发语言
Y3815326627 小时前
SERP 数据清洗实战:字段标准化、日期解析与去重键
开发语言·数据库·python·python数据库