2010-02-08 8 views
52

폴더 및 폴더 내의 모든 파일 및 폴더를 삭제하려고하는데 아래 코드를 사용하면 오류가 발생합니다. Folder is not empty, 어떤 제안 사항이 있습니까? 내가 할 수있는?C# 폴더 및 폴더 내의 모든 파일 및 폴더 삭제

try 
{ 
    var dir = new DirectoryInfo(@FolderPath); 
    dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly; 
    dir.Delete(); 
    dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i].Index); 
} 
catch (IOException ex) 
{ 
    MessageBox.Show(ex.Message); 
} 

답변

84
dir.Delete(true); // true => recursive delete 
54

수동 읽기 : 당신이

+14

왜 Google을 빨리 읽었습니까? – reggaeguitar

+0

true로 설정하면 path의 모든 dir, subdir 및 파일이 삭제됩니다. 경로 자체도 삭제됩니까? false로 설정하면 경로가 삭제되고 path의 하위 디렉토리와 파일은 삭제됩니까? – helloworld

4

, 그것은해야 할 무엇 막 전화 Directory.Delete(path, true);?

+0

true로 설정하면 경로의 모든 디렉토리, 하위 디렉토리 및 파일이 삭제됩니다. 경로 자체도 삭제됩니까? false로 설정하면 경로가 삭제되고 경로의 하위 디렉토리와 파일에 대한 정보가 표시됩니다. – helloworld

6

잘못을 필요

Directory.Delete Method (String, Boolean)

Directory.Delete(folderPath, true); 
Directory.Delete 방법은 재귀 부울 매개 변수가
+0

true로 설정하면 경로의 모든 디렉토리, 하위 디렉토리 및 파일이 삭제됩니다. 경로 자체도 삭제됩니까? false로 설정하면 경로가 삭제되고 path의 하위 디렉토리와 파일은 삭제됩니까? – helloworld

18

시도 :

System.IO.Directory.Delete(path,true) 

이 반복적으로 사용하면 권한이 그렇게해야 할 가정 "경로"아래에있는 모든 파일과 폴더를 삭제합니다.

+0

true로 설정하면 path의 모든 dir, subdir 및 파일이 삭제됩니다. 경로 자체도 삭제됩니까? false로 설정하면 경로가 삭제되고 path의 하위 디렉토리와 파일은 삭제됩니까? – helloworld

3

당신은 사용해야

dir.Delete(true); 

를 재귀 적으로도 해당 폴더의 내용을 삭제하는. MSDN DirectoryInfo.Delete() overloads을 참조하십시오.

+0

true로 설정하면 path의 모든 dir, subdir 및 파일이 삭제됩니다. 경로 자체도 삭제됩니까? false로 설정하면 경로가 삭제되고 path의 하위 디렉토리와 파일은 삭제됩니까? – helloworld

0
public void Empty(System.IO.DirectoryInfo directory) 
{ 
    try 
    { 
     logger.DebugFormat("Empty directory {0}", directory.FullName); 
     foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete(); 
     foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true); 
    } 
    catch (Exception ex) 
    { 
     ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture)); 

     throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex); 
    } 
} 
2

시도해보십시오.

namespace EraseJunkFiles 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\"); 
      foreach (DirectoryInfo dir in yourRootDir.GetDirectories()) 
        DeleteDirectory(dir.FullName, true); 
     } 
     public static void DeleteDirectory(string directoryName, bool checkDirectiryExist) 
     { 
      if (Directory.Exists(directoryName)) 
       Directory.Delete(directoryName, true); 
      else if (checkDirectiryExist) 
       throw new SystemException("Directory you want to delete is not exist"); 
     } 
    } 
}