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

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

相关推荐
时光追逐者10 分钟前
C# 哈希查找算法实操
算法·c#·哈希算法
wanzhong233344 分钟前
学习triton-第1课 向量加法
开发语言·python·高性能计算
三千道应用题1 小时前
C#语言入门详解(18)传值、输出、引用、数组、具名、可选参数、扩展方法
开发语言·c#
micoos1 小时前
C#-LinqToObject-Element
c#
忧郁的蛋~1 小时前
使用.NET标准库实现多任务并行处理的详细过程
开发语言·c#·.net
dragon_perfect1 小时前
全流程基于Yolov8实现在Label-Studio实现半自动标注,已经把整个流程理清楚,把所有的坑解决。
开发语言·python·yolo·labelstudio
kalvin_y_liu1 小时前
四款主流深度相机在Python/C#开发中的典型案例及技术实现方案
开发语言·python·数码相机
劲镝丶1 小时前
malloc概述
c语言·开发语言·c++
1373i2 小时前
【Python】pytorch数据操作
开发语言·pytorch·python
努力努力再努力wz2 小时前
【C++进阶系列】:万字详解红黑树(附模拟实现的源码)
java·linux·运维·c语言·开发语言·c++