• C#写入文件时报:System.UnauthorizedAccessException错误
  • 发布于 2个月前
  • 366 热度
    0 评论
使用 System.IO.File.WriteAllText 方法可以很轻松的将文字内容写入文件:
File.WriteAllText(@"D:\test.txt","https://www.duidaima.com");
但如果要写入的文件比较特殊,就会抛出 UnauthorizedAccessException 异常:
System.UnauthorizedAccessException: 对路径“D:\test.txt”的访问被拒绝。
在 .NET 7.0 中的提示大概是这样:
System.UnauthorizedAccessException: Access to the path 'D:\test.txt' is denied.
当遇到 UnauthorizedAccessException 异常时,第一个反应就是权限不足。如果提升管理员权限仍无法解决时,就需要考虑目标文件是否是只读(ReadOnly)的或者被隐藏(Hidden)。

在 dotnet 中,FileInfo 类型提供了 IsReadOnly 和 Attributes 两个属性来便于我们操作文件。以下代码完成了去掉文件“只读”和“隐藏”标记的功能:
var info = new FileInfo(@"D:\test.txt");
//只有已存在的文件才能操作其属性
if (info.Exists)
{
//去掉只读属性
if (info.IsReadOnly) info.IsReadOnly = false;
//去掉隐藏属性
if (info.Attributes.HasFlag(FileAttributes.Hidden)) info.Attributes &= ~FileAttributes.Hidden;
}
//写入文件内容
File.WriteAllText(@"D:\test.txt","https://www.duidaima.com");

用户评论