Exception codes, or detecting a "file already exists" type exception

GazTheDestroyer picture GazTheDestroyer · Sep 12, 2012 · Viewed 27.5k times · Source

In trying to answer this question, I was surprised to discover that attempting to create a new file when that file already exists does not throw a unique exception type, it just throws a generic IOException.

I am therefore left wondering how to determine if the IOException is the result of an existing file, or some other IO error.

The exception has an HResult, but this property is protected, and thus unavailable to me.

The only other way I can see is to pattern match the message string which feels awful.

example:

try
{
    using (var stream = new FileStream("C:\\Test.txt", FileMode.CreateNew))
    using (var writer = new StreamWriter(stream))
    {
        //write file
    }
}
catch (IOException e)
{
    //how do I know this is because a file exists?
}

Answer

jgauffin picture jgauffin · Sep 12, 2012
try
{
    using (var stream = new FileStream("C:\\Test.txt", FileMode.CreateNew))
    using (var writer = new StreamWriter(stream))
    {
        //write file
    }
}
catch (IOException e)
{
    var exists = File.Exists(@"C:\Text.text"); // =)
}

Won't work for temp files etc which might have been deleted again.

Here are my exception best practices: https://coderr.io/exception-handling