Study/.NET (C#, WPF, Unity)

[C#] 디렉토리 (폴더) 삭제에 관하여

BlueBright 2019. 8. 23. 09:45

폴더를 삭제할 일이 존재하여서 웹을 뒤져보았다.

 

 

Directory.Delete("path",true);

 

DirectoryInfo di = new DirectoryInfo("Path");
di.Delete(true);

 

foreach (string file in Directory.GetFiles(@"c:\directory\"))
  File.Delete(file);

 

삭제를 하는 함수들은 여러가지가 존재했지만, 제대로 작동하는 것이 없었다.

그 원인들을 분석해보니

 

  • System.IO.IOException : The directory is not empty 
  • 경로를 찾지 못함
  • 권한(?) 문제
  • 읽기 전용
  • .NET 버전에 따라 함수가 다른 기능을 할 수도 있음
  • 이외 여러가지(?)

 

Exception이 발생해서 해당 폴더를 살펴 보면, 막상 내부는 깨끗이 삭제된 경우도 간혹 있었다.

 

답변들을 좀 더 자세히 읽어보니, 파일(또는 폴더) 삭제되었다는 것을 인지하기도 전에 다른 파일(또는 폴더)를 삭제하려는 시도를 하기 때문에 (즉, 파일을 삭제하는 속도가 너무 빨라서)  발생하는 현상. 또는 다른 프로그램(Explorer, 백신)과의 충돌이 다른 가능성이라고 한다.

 

/// <summary>
/// Depth-first recursive delete, with handling for descendant 
/// directories open in Windows Explorer.
/// </summary>
public static void DeleteDirectory(string path)
{
    foreach (string directory in Directory.GetDirectories(path))
    {
        DeleteDirectory(directory);
    }

    try
    {
        Directory.Delete(path, true);
    }
    catch (IOException) 
    {
        Directory.Delete(path, true);
    }
    catch (UnauthorizedAccessException)
    {
        Directory.Delete(path, true);
    }
}

https://stackoverflow.com/a/1703799/7017299

 

Cannot delete directory with Directory.Delete(path, true)

I'm using .NET 3.5, trying to recursively delete a directory using: Directory.Delete(myPath, true); My understanding is that this should throw if files are in use or there is a permissions proble...

stackoverflow.com

 

그나마 적합하다고 생각되는 해결 방법은 Exception을 우회 하거나, Thread.Sleep(밀리세컨드)를 주는 것.

Console.WriteLine()의 결과를 보면 Exception이 여전히 발생하기는 하지만, 파일 (폴더)는 잘 삭제한다.

 

'Study > .NET (C#, WPF, Unity)' 카테고리의 다른 글

[C#] Helix-toolkit 연구중 (WPF.SharpDX 기준)  (0) 2021.01.27
[Unity] Windows Magic Leap 초기 설정  (0) 2020.12.08
[C#] 배열 연구  (0) 2020.01.07
[C#] 문법 공부중입니다  (0) 2018.05.17