FileAttributes Enum
https://docs.microsoft.com/en-us/dotnet/api/system.io.fileattributes?view=netframework-4.7.2
读取FileAttributes
在桌面新建一个文件file-to-delete.txt,设置只读属性。先删除,然后从回收站还原
[Test] public void FileAttributeTest() { var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var fileName = "file-to-delete.txt"; var path = Path.Combine(desktop, fileName); var attributes = File.GetAttributes(path); Console.WriteLine(attributes); }
输出结果为 ReadOnly, Archive
尝试删除一个只读文件
static void Main(string[] args) { try { var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var fileName = "file-to-delete.txt"; var path = Path.Combine(desktop, fileName); Console.WriteLine(); if (File.Exists(path)) { Console.WriteLine(File.GetAttributes(path)); File.Delete(path); } } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } }
ReadOnly
System.UnauthorizedAccessException: Access to the path 'C:\Users\clu\Desktop\file-to-delete.txt' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalDelete(String path, Boolean checkHost)
at System.IO.File.Delete(String path)
at ConsoleApp2.Program.Main(String[] args) in C:\Users\clu\source\repos\Edenred\Test\ConsoleApp2\Program.cs:line 19
设置FileAttributes
方法1
File.SetAttributes(path, FileAttributes.Normal);
方法2
FileInfo info = new FileInfo(path) {Attributes = FileAttributes.Normal};
if (File.Exists(path)) { Console.WriteLine(File.GetAttributes(path));
FileInfo info = new FileInfo(path) {Attributes = FileAttributes.Normal};
Console.WriteLine(File.GetAttributes(path)); File.Delete(path); }
How do I delete a directory with read-only files in C#?
Simplest way of avoiding recursive calls is by utilising the AllDirectories
option when getting FileSystemInfo
s, like so:
public static void ForceDeleteDirectory(string path) { var directory = new DirectoryInfo(path) { Attributes = FileAttributes.Normal }; foreach (var info in directory.GetFileSystemInfos("*", SearchOption.AllDirectories)) { info.Attributes = FileAttributes.Normal; } directory.Delete(true); }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-03-29 单元测试实战
2016-03-29 如何查看单元测试的结果 以及异常处理
2016-03-29 Expression Trees (C# and Visual Basic)
2016-03-29 LINQ Query Expressions