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

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

相关推荐
MATLAB代码顾问21 分钟前
MATLAB实现多种群遗传算法
开发语言·matlab
叫我DPT41 分钟前
Go 中 defer 的机制
开发语言·后端·golang
幻想趾于现实1 小时前
C# 装箱和拆箱(以及 as ,is)
开发语言·c#
xcLeigh1 小时前
WPF进阶 | WPF 动画特效揭秘:实现炫酷的界面交互效果
c#·wpf·交互
VB.Net1 小时前
17.3.5 添加水印
矩阵·c#·水印
谢大旭2 小时前
ASP.NET Core自定义 MIME 类型配置
后端·c#
好好学Java吖3 小时前
【二分题目】
java·开发语言
米码收割机3 小时前
【PHP】基于 PHP 的图片管理系统(源码+论文+数据库+图集)【独一无二】
开发语言·数据库·php
yyytucj3 小时前
优化 PHP-FPM 参数配置:实现服务器性能提升
服务器·开发语言·php
鲤籽鲲3 小时前
C# 中 [MethodImpl(MethodImplOptions.Synchronized)] 的使用详解
java·开发语言·c#