Domanda

In the MSDN documentation for System.IO.Directory.Delete(string, bool) (here) it says that DirectoryNotFoundException is thrown when "path refers to a file instead of a directory.".

However, the following test fails because IOException is thrown:

[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);
}

with

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

(tempPath is deleted after each test in the real code, the above is shortened for illustration). Is my test to force this error wrong or is the documentation not correct?

È stato utile?

Soluzione

I think that the documentation is right, but there is a trick.
When you call DeleteDirectory passing an existent file the first exception thrown is a

IOException ...... A file with the same name and location specified by path exists.

You can prove this with

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); 

Now, if you try to pass a file name that doesn't exist the exception DirectoryNotFoundException is thrown as expected.

Altri suggerimenti

The file that you are attempting to delete is not a directory and io exception is thrown because "A file with the same name and location specified by path exists." Which is one of ioexception listed reasons

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top