// 判断文件是否为只读
public bool IsFileReadOnly(string filePath)
{
try
{
// 获取文件的属性
FileAttributes attributes = File.GetAttributes(filePath);
// 检查只读属性
return (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
}
catch (Exception ex)
{
Console.WriteLine($"检查文件属性时出错: {ex.Message}");
throw;
}
}
// 将文件修改为可读可写
public void MakeFileReadWrite(string filePath)
{
try
{
// 获取文件的当前属性
FileAttributes attributes = File.GetAttributes(filePath);
// 移除只读属性 (使用按位与NOT操作符)
attributes = attributes & ~FileAttributes.ReadOnly;
// 应用修改后的属性
File.SetAttributes(filePath, attributes);
}
catch (Exception ex)
{
Console.WriteLine($"修改文件属性时出错: {ex.Message}");
throw;
}
}这个操作需要对文件所在目录有写权限
如果文件正在被其他程序占用,修改属性可能会失败
在修改系统文件或受保护的文件时可能需要管理员权限
该方法只修改文件的只读属性,不会影响其他属性(如隐藏、系统等)
如果是系统文件,需要管理员权限,可以用这个方法,以管理员身份运行
https://www.luofenming.com/show.aspx?id=2024051222270721
这是C# 判断是否以管理员身份运行,如果不是管理员身份则以管理员身份运行
本文来自www.luofenming.com