2013-11-26 2 views
1

System.IO.Directory.Delete (문자열, 부울) (here)에 대한 MSDN 설명서에서 "경로가 디렉터리 대신 파일을 참조 할 때"DirectoryNotFoundException이 throw됩니다. 예외 : IOException가 발생하기 때문에Directory.Delete에 관한 MSDN 설명서가 잘못 되었습니까?

그러나 다음 테스트가 실패 :

[Test] 
[ExpectedException(typeof(DirectoryNotFoundException))] // because DeleteDirectory fails on files. 
public void DeleteFileWithDeleteDirectoryDirectly() 
{ 
    var tempPath = Path.Combine(Path.GetTempPath(), "MyTestDirectory"); 
    Directory.CreateDirectory(tempPath); 
    string file = Path.Combine(tempPath, "File1235.txt"); 
    CreateDummyFile(file); 
    Assert.That(File.Exists(file)); 
    Directory.Delete(file, true); 
} 

void CreateDummyFile(string name) 
{ 
    FileStream fs = File.Open(name, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); 
    fs.WriteByte(255); 
    fs.Close(); 
} 

로 (tempPath 위의 그림에 대한 단축, 실제 코드에서 각 테스트 후 삭제됩니다). 이 오류를 강제로 내 테스트가 잘못 되었습니까? 아니면 설명서가 올바르지 않습니까?

+0

여기에서 재현 할 수 없습니다. IOException 던져 –

+0

그건 내가 말하는거야. IOException이 발생하지만 DirectoryNotFoundException이 필요합니다. – PMF

답변

2

설명서가 맞다고 생각하지만 트릭이 있습니다.
당신이 DeleteDirectory이 존재하지 않는 파일을 던진 최초의 예외를 통과 부르는

IOException이 ...... 이 존재하는 경로에 의해 지정된 동일한 이름과 위치의 파일입니다. 당신이 예상대로 예외 DirectoryNotFoundException가 발생 존재하지 않는 파일 이름을 전달하려고하면

당신은 지금

var tempFile = Path.Combine(Path.GetTempPath(), "MyTestDirectory", "inexistentfile.txt"); 
var tempPath = Path.Combine(Path.GetTempPath(), "MyTestDirectory"); 
Directory.CreateDirectory(tempPath); 
string file = Path.Combine(tempPath, "File1235.txt"); 
CreateDummyFile(file); 
if(File.Exists(file)) Console.WriteLine("File exists"); 
Directory.Delete(tempFile, true); 

이것을 증명할 수 있습니다.

+1

예, 그게 전부입니다. 여전히 혼란스러운 행동. – PMF

0

삭제하려는 파일이 디렉토리가 아니며 "경로로 지정한 이름과 위치의 파일이 있습니다"때문에 io 예외가 발생합니다. io 예외 목록에있는 이유 중 하나입니다