0

What I have is a basic program to delete folders created on a given date. The program runs and works however, it's not evaluating sub-directories. Is there something that I am doing wrong or not considering.

Thank you for your help.

Imports System.IO

Public Class FormMain

    Private Sub btn_DeleteFolders_Click(sender As Object, e As EventArgs) Handles btn_DeleteFolders.Click

            Dim myDate As Date = dt_FolderDate.Value.Date
            Dim myRoot As New DirectoryInfo(tb_UNC.Text)

            If tb_UNC.Text Is Nothing Then
                MessageBox.Show("Please select a directory")
            End If

            If Not myRoot.Exists Then
                MessageBox.Show("Directory doesn't exist")
                Exit Sub
            End If


            For Each myDir In myRoot.EnumerateDirectories("*", SearchOption.AllDirectories)
                If myDir.CreationTime.Date = myDate Then
                    myDir.Delete(True)
                End If
            Next
        End If
    End Sub



End Class
4

2 回答 2

0

如果是我,我会编写一个从事件处理程序调用的递归方法。该方法将根目录的路径作为参数。在该方法中,我将遍历提供的目录下的子目录,然后 a.) 根据需要删除子目录或 b.) 递归调用子目录上的方法。

像这样的东西:

Private Sub Recurse(OnFolderPath As String)
    For Each strSubDir In Directory.GetDirectories(OnFolderPath)
        If (New DirectoryInfo(strSubDir).CreationTime.Date = MyDate) Then
            Directory.Delete(strSubDir)
        Else
            Recurse(strSubDir)
        End If
    Next
End Sub

如果您想避免重解析点(也称为连接点)的问题,正如 bhs 指出的那样,您可以包含这样的函数:

Public Function IsJunctionPoint(ByVal ToCheck As DirectoryInfo) As Boolean
    'if the directory has the attributes which indicate that it's a junction point...
    If (((ToCheck.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden) And
        ((ToCheck.Attributes And FileAttributes.System) = FileAttributes.System) And
        ((ToCheck.Attributes And FileAttributes.ReparsePoint) = FileAttributes.ReparsePoint)) Then

        Return True
    Else 'is not a junction point...
        Return False
    End If
End Function

然后你会在你的递归方法中使用它来避免这些。

于 2013-09-25T15:03:12.890 回答
0

您还偶然发现(或很快会做)我最近遇到的一个问题。

EnumerateDirectories如果您尝试枚举您对or方法没有权限的文件或文件夹,EnumerateFolders则会简单地停止并抛出异常。

捕获异常也会导致它停止。这几乎肯定不是您想要的行为。

我在这里找到了一个递归解决方案,并在这个SO 页面上实现了一个名为FindAccessableFiles(我认为它可能是最后一个化身)的方法,它工作得非常好。

private static IEnumerable<String> FindDeletableFolders(string path, string file_pattern, bool recurse)
        {
            IEnumerable<String> emptyList = new string[0];

            if (File.Exists(path))
                return new string[] { path };

            if (!Directory.Exists(path))
                return emptyList;

            var top_directory = new DirectoryInfo(path);

            // Enumerate the files just in the top directory.
            var files = top_directory.EnumerateFiles(file_pattern).ToList();
            var filesLength = files.Count();
            var filesList = Enumerable
                      .Range(0, filesLength)
                      .Select(i =>
                      {
                          string filename = null;
                          try
                          {
                              var file = files.ElementAt(i);
                              filename = file.Name; // add your date check here                              }
                          catch (FileNotFoundException)
                          {
                          }
                          catch (UnauthorizedAccessException)
                          {
                          }
                          catch (InvalidOperationException)
                          {
                              // ran out of entries
                          }
                          return filename;
                      })
                      .Where(i => null != i);

            if (!recurse)
                return filesList;

            var dirs = top_directory.EnumerateDirectories("*");
            var dirsLength = dirs.Count();
            var dirsList = Enumerable
                .Range(0, dirsLength)
                .SelectMany(i =>
                {
                    string dirname = null;
                    try
                    {
                        var dir = dirs.ElementAt(i);
                        dirname = dir.FullName;
                        if (dirname.Length > 0)
                        {
                            var folderFiles = FindDeletableFolders(dirname, file_pattern, recurse).ToList();
                            if (folderFiles.Count == 0)
                            {
                                try
                                {
                                        Directory.Delete(dirname);
                                }
                                catch
                                {
                                }
                            }
                            else
                            {
                                return folderFiles;
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                    }
                    catch (InvalidOperationException)
                    {
                        // ran out of entries
                    }
                    return emptyList;
                });
            return Enumerable.Concat(filesList, dirsList).ToList();
        }

我不得不破解我的一些代码,所以在使用前检查功能并测试它。

该代码将返回一个可以删除的文件夹列表,并删除它遇到的空文件夹。

于 2013-09-25T15:04:11.520 回答