2013-09-25 6 views
0

주어진 날짜에 만들어진 폴더를 삭제하는 기본 프로그램이 있습니다. 프로그램이 실행되고 작동하지만 서브 디렉토리를 평가하지는 않습니다. 내가 잘못하고 있거나 생각하고 있지 않은 무언가가 있는가?VB.net에서 디렉터리 및 하위 디렉터리를 열거하는 방법

도움 주셔서 감사합니다.

+0

루틴에서 "* 하위 디렉토리 평가 중 *"이라고 생각했던 곳은 어디입니까? – RBarryYoung

+0

SearchOption.AllDirectories 인수를 사용하여 for 루프에서 평가 중이라고 가정합니다. – BSanders

+0

좋습니다. Doc가 해당 검색 옵션 (저조한 이름의 IMHO)에 대해 말합니다. – RBarryYoung

답변

0

내 경우에는 이벤트 처리기에서 호출하는 재귀 적 메서드를 작성합니다. 이 메소드는 루트 디렉토리에 대한 경로를 인수로 취합니다. 메서드 내에서 제공된 디렉터리 아래의 하위 디렉터리를 반복하고 필요한 경우 하위 디렉터리를 삭제하거나 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 

그러면 재귀 적 방법을 사용하여이를 피할 수 있습니다.

+0

어떻게하면됩니까? – BSanders

0

최근 발생한 문제에 대해 비틀 거리거나 곧 해결할 것입니다.

EnumerateDirectories 또는 EnumerateFolders 메서드에 대한 사용 권한이없는 파일이나 폴더를 열거하면 단순히 중지되고 예외가 throw됩니다.

예외를 트래핑하면 중지됩니다. 이것은 거의 당신이 원하는 행동이 아닙니다.

여기서 재귀적인 해결책을 발견하고이 SO page에 대한 방법을 구현했습니다. 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(); 
     } 

코드를 일부 해킹하여 기능을 확인하고 사용하기 전에 테스트해야했습니다.

코드는 삭제할 수있는 폴더 목록을 반환하고 해당 폴더가 비어있는 폴더도 삭제합니다.

관련 문제