2012-08-17 2 views
1

시스템 스레드를 사용하여 폴더를 반복하면서 파일 액세스가 거부되면 무시하고 계속하는 방법.파일에 대한 액세스가 거부되면 스레드 캐치 계속

// Start thread. 
System.Threading.ThreadStart start = delegate { scanner(@"C:\", "*.html;*.txt"); }; 
System.Threading.Thread thread = new System.Threading.Thread(start); 
thread.Start(); 


private static string scanstatus = string.Empty; 
private static void scanner(string folder, string patterns) 
{ 
    try 
    { 
     // Get the patterns. 
     string[] pattern_array = patterns.Split(';'); 

     // Search. 
     foreach (string pattern in pattern_array) 
     { 
      foreach (string path in System.IO.Directory.GetFiles(folder, pattern, System.IO.SearchOption.AllDirectories)) 
      { 
       // trim path 
       scanstatus = (path.Length > 60) ? "../" + path.Substring(path.Length - 59, 59) : path; 

       System.Threading.Thread.Sleep(5000); 
      } 
     } 

    } 
    catch (System.Exception excpt) 
    { 
     Console.WriteLine(excpt.Message); 
    } 
    finally 
    { 
     Console.WriteLine("*************DONE*************"); 
    } 

} 
+2

'try-catch'를 루프 안에 넣는 것이 무슨 문제입니까? –

+0

계속되지 않습니다. 내가 뭘 잘못했는지 모르겠다. –

+0

루프 내부에'try-catch' **를 넣어야한다. 당신은 ** 외부 루프 **를 가지고 있습니다 ... –

답변

2

Daniel이 주석에서 언급했듯이 기본적으로 다음 반복을 계속 진행하려면 try/catch를 루프 내부로 이동해야합니다. 현재 catch가 외부의 외부 루프이므로 예외가 throw되면 실행을 계속할 수 없습니다. C# 내에서 "어디로 가야할지 계속하라"는 개념이 없습니다.

나는 잡는 것을 제한 할 것을 강력히 제안합니다.

foreach (string pattern in patternArray) 
{ 
    try 
    { 
     foreach (string path in Directory.GetFiles(...)) 
     { 
      // ... 
     } 
    } 
    catch (IOException e) 
    { 
     // Log it or whatever 
    } 
    // Any other exceptions you want to catch? 
} 

주 : 예를 들어

  • 는 변수에
  • 밑줄을 처리 요청 (또는 무엇이든)의 최상위 레벨에 최종 포수를 제외하고, 거의 항상 나쁜 생각을 Exception입니다 잡기 .NET에서는 이름이 일반적이지 않습니다. 일반적으로 훨씬 쉽게
  • 이 방법을 읽을 수 있도록 할 코드에서 정규화 된 형식 이름을 넣어 피할 수 using 지시어로 (메소드, 클래스 등과 PascalCase) 변수에 CamelCase
  • 을 사용하십시오 꽤 오래 끝날 것입니다 - 내부 루프를 추출하는 것이 좋습니다; 아마도 try/catch를 포함하거나 가능하지 않을 수도 있습니다.
+0

당신이 제안한대로 계속했습니다. 계속하지 않습니다. –

+0

이것은 나를 위해 작동하지 않습니다. 특히 엑셀 파일의 경우,이 행은 멈추고 예외는 발생하지 않습니다 :'wb = excel.Workbooks.Open (filePath, false, true, 5, null, "WrongPAssword");'. 허가가 있는지 테스트하는 방법을 알고 있습니까? –

+0

@ Power-Mosfet : 글쎄, *할까요? 예외가 슬로우되면 (자), 다음의 thread로 계속 진행됩니다. –

관련 문제