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

 

 

posted @ 2019-03-29 11:27  ChuckLu  阅读(581)  评论(0编辑  收藏  举报