c# - 如何在遍历文件夹树时删除文件

标签 c# filesystems delete-file

我不确定我这样做是否正确,或者我的逻辑是否正确。

我正在尝试沿着文件夹结构删除超过一定天数的文件,这部分我已经正确实现,删除空文件夹。

所有这些都可以在一个循环中完成吗?
我在哪里删除文件夹?

我想删除最多 3 或 4 级的空文件夹。

    private static void TraverseTree(System.IO.DirectoryInfo folder, double days)
    {
        Stack<string> dirs = new Stack<string>();

        if (!folder.Exists)
            throw new ArgumentException();

        dirs.Push(folder.FullName);

        while (dirs.Count > 0)
        {
            string currentDir = dirs.Pop();
            string[] subDirs;
            try
            {
                subDirs = System.IO.Directory.GetDirectories(currentDir);
            }
            // An UnauthorizedAccessException exception will be thrown if we do not have
            // discovery permission on a folder or file. It may or may not be acceptable 
            // to ignore the exception and continue enumerating the remaining files and 
            // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
            // will be raised. This will happen if currentDir has been deleted by
            // another application or thread after our call to Directory.Exists. The 
            // choice of which exceptions to catch depends entirely on the specific task 
            // you are intending to perform and also on how much you know with certainty 
            // about the systems on which this code will run.
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            string[] files = null;
            try
            {
                files = System.IO.Directory.GetFiles(currentDir);
            }
            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                continue;
            }

            // Perform the required action on each file here.
            // Modify this block to perform your required task.
            foreach (string file in files)
            {
                try
                {
                    // Perform whatever action is required in your scenario.
                    System.IO.FileInfo fi = new System.IO.FileInfo(file);
                    Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);

                    // Delete old files
                    if (fi.LastWriteTime < DateTime.Now.AddDays(-days))
                        fi.Delete();
                }
                catch (System.IO.FileNotFoundException e)
                {
                    // If file was deleted by a separate application
                    //  or thread since the call to TraverseTree()
                    // then just continue.
                    Console.WriteLine(e.Message);
                    continue;
                }
            }

            // Push the subdirectories onto the stack for traversal.
            // This could also be done before handing the files.
            foreach (string str in subDirs)
                dirs.Push(str);
        }
    }

代码来自MSDN .

最佳答案

递归方法可能会更清晰。

private static void DeleteOldFilesAndFolders(string path)
{
    foreach (string directory in System.IO.Directory.GetDirectories(path))
    {
        DeleteOldFilesAndFolders(directory);

        // If the directory is empty and old, delete it here.
    }

    foreach (string file in System.IO.Directory.GetFiles(path))
    {
        // Check the file's age and delete it if it's old.
    }
}

关于c# - 如何在遍历文件夹树时删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1369616/

相关文章:

c# - 在一个消息框中列出所有组合框项目

linux - 关于Linux文件系统

mysql - 我可以安全地从 mysql 数据库中删除 .BAK 文件吗?

java - 从 SD 卡和 gridview 中删除选定的视频

c# - JWT Middleware 未从 OpenIddict Issued JWT 获得声明

c# - 使用 C# 过滤 MongoDB 日期范围之间的数据

javascript - 将 PNG Canvas 图像保存到 HTML5 存储(JavaScript)?

linux - 每个驱动器的最大文件数

javascript - 不允许使用 Codeigniter/PHP(405 错误)在 jQuery Blueimp FileUpload 上删除方法?

c# - Silverlight 嵌套自定义控件导致 StackOverflowException