Search code examples
c#exceptionioexceptionfile-exists

Exception Thrown in C# for FileStream Constructor with CreateNew for Existing File


I am creating a file in C# (.NET Web Service) and do not want to overwrite an existing file.

The way seems to be to construct a FileStream with FileMode.CreateNew set. It does in fact throw an exception if the file exists.

But how do I recognize this exception as opposed to other possible exceptions thrown by the file creation? The documentation at http://msdn.microsoft.com/en-us/library/47ek66wy.aspx lists this case as an "IOException" which clearly is vague as other things can cause this.

Is the answer here that I catch IOException and then just do a File.Exists?


Solution

  • You can get error code from the exception as the following:

    int hr = Marshal.GetHRForException( ex );
    

    For file exists it will be 0x80070050.