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

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

你可能感兴趣的:(c#,开发语言)