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

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

相关推荐
tryxr14 分钟前
Java 多线程标志位的使用
java·开发语言·volatile·内存可见性·标志位
APItesterCris26 分钟前
高并发场景下的挑战:1688 商品 API 的流量控制、缓存策略与异步处理方案
大数据·开发语言·数据库·缓存
yyy(十一月限定版)27 分钟前
c语言——栈和队列
java·开发语言·数据结构
feeday29 分钟前
Python 删除重复图片 优化版
开发语言·python
.格子衫.33 分钟前
JS原型链总结
开发语言·javascript·原型模式
麦麦鸡腿堡36 分钟前
Java_MySQL介绍
java·开发语言·mysql
于是我说36 分钟前
一份Python 面试常见问题清单 覆盖从初级到高级
开发语言·python·面试
shoubepatien36 分钟前
JavaWeb_Web基础
java·开发语言·前端·数据库·intellij-idea
吧啦蹦吧1 小时前
`org.springframework.util.ClassUtils#forName
开发语言·python
CC.GG1 小时前
【C++】红黑树
java·开发语言·c++