C# 如何向隐藏(Hidden)只读(ReadOnly)文件写入内容?

使用 System.IO.File.WriteAllText 方法可以很轻松的将文字内容写入文件:

File.WriteAllText(@"D:\test.txt","https://www.coderbusy.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.coderbusy.com");

FileInfo : 

https://learn.microsoft.com/zh-cn/dotnet/api/system.io.fileinfo?view=net-7.0