c# 让文件只读

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

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方法将更新后的属性设置回文件。

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

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

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

相关推荐

  1. c# 文件

    2024-01-01 06:54:05       32 阅读
  2. C#中字典、列表、数组作为的方法参考

    2024-01-01 06:54:05       18 阅读
  3. Oracle 23C用户模式不错!

    2024-01-01 06:54:05       11 阅读
  4. C++ 在堆或栈上分配

    2024-01-01 06:54:05       21 阅读
  5. c++的文件

    2024-01-01 06:54:05       36 阅读
  6. C++的文件

    2024-01-01 06:54:05       45 阅读
  7. C++写BMP文件

    2024-01-01 06:54:05       16 阅读
  8. C语言】文件

    2024-01-01 06:54:05       24 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-01 06:54:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-01 06:54:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-01 06:54:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-01 06:54:05       18 阅读

热门阅读

  1. Prometheus监控nginx

    2024-01-01 06:54:05       36 阅读
  2. 在Neo4j中实现推荐算法

    2024-01-01 06:54:05       37 阅读
  3. 数据挖掘与知识发现:解析关键概念

    2024-01-01 06:54:05       25 阅读
  4. 常用的几种包管理器 npm yarn cnpm pnpm 安装

    2024-01-01 06:54:05       41 阅读
  5. 计算机基础--Linux详解

    2024-01-01 06:54:05       33 阅读
  6. 第82讲:MySQL Binlog日志的滚动

    2024-01-01 06:54:05       35 阅读
  7. git 命令

    2024-01-01 06:54:05       38 阅读
  8. yii2 mysql重连机制

    2024-01-01 06:54:05       37 阅读
  9. 基于SpringBoot的电影购票系统

    2024-01-01 06:54:05       36 阅读
  10. 【算法】数论---快速幂

    2024-01-01 06:54:05       42 阅读
  11. 剑指offer题解合集——Week2day6

    2024-01-01 06:54:05       42 阅读
  12. C语言之冒泡排序

    2024-01-01 06:54:05       34 阅读
  13. SQL高级:存储过程和触发器

    2024-01-01 06:54:05       36 阅读
  14. Linux常用命令总结

    2024-01-01 06:54:05       35 阅读