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

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

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值