2016-07-15 2 views
0

기준과 일치하는 모든 파일을 검색하는 모든 드라이브에서 모든 디렉터리를 반복하는 코드를 함께 자갈로 묶었습니다. 일치하는 파일의 파일 이름을 간단한 Windows Form ("textBox1.Text = fi1.FullName;")에 작성하여 각 디렉토리를 처리하는 동안 검색 진행 상황을 문서화하고 싶습니다. 검색이 완료 될 때까지 양식이 보이지 않습니다. Window Form은 검색이 끝날 때까지 비활성 상태이므로 의심 스럽지만 (이렇게 쓰는 것은 효과가 없습니다.) 검색 중에 양식을 보이게하려면 어떻게해야하는지 확신 할 수 없습니다. 누군가가 잠시 시간을내어 코드를보고 나에게 조언 할 수 있는지 물어봐도 될까요?간단한 Windows Form이 표시되지 않음

도움 주셔서 감사합니다.

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Windows.Forms; 

namespace FindFiles 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      var searchPattern = ".jpg"; 
      var matchedFiles = FindMatchingFiles(searchPattern); 
     } 

     private List<string> FindMatchingFiles(string searchPattern) 
     { 
      var l = new List<string>(); 
      var allDrives = DriveInfo.GetDrives(); 

      foreach (var d in allDrives.Where(d => d.IsReady)) 
      { 
       foreach (var file in GetFiles(d.Name)) 
       { 
        if (!file.EndsWith(searchPattern)) continue; 
        var fi1 = new FileInfo(file); 
        textBox1.Text = fi1.FullName; 
        l.Add(file); 
       } 
      } 
      return l; 
     } 

     static IEnumerable<string> GetFiles(string path) 
     { 
      var queue = new Queue<string>(); 
      queue.Enqueue(path); 
      while (queue.Count > 0) 
      { 
       path = queue.Dequeue(); 
       try 
       { 
        foreach (var subDir in Directory.GetDirectories(path)) 
        { 
         queue.Enqueue(subDir); 
        } 
       } 
       catch (UnauthorizedAccessException) { } 
       string[] files = null; 
       try { files = Directory.GetFiles(path); } 
       catch (UnauthorizedAccessException) { } 
       if (files == null) continue; 
       foreach (var t in files) { yield return t; } 
      } 
     } 
    } 
} 

답변

1

검색 코드가 UI 스레드에서 실행되고있는 것이 문제입니다. 검색 코드가 완료 될 때까지 UI가 업데이트되지 않습니다.

UI를 차단하지 않고 장기 실행 코드를 실행하기 위해 BackgroundWorker 및 ReportProgress 메커니즘을 살펴보십시오.

+0

https://msdn.microsoft.com/en-gb/library/cc221403(v=vs.95).aspx 도움이 될 수 있습니다. –

+0

완벽한 솔루션 JSR. 고맙습니다. – Bill

관련 문제