Reputation: 73
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?
Upvotes: 4
Views: 1802
Reputation: 3975
You can get error code from the exception as the following:
int hr = Marshal.GetHRForException( ex );
For file exists it will be 0x80070050.
Upvotes: 5
Reputation: 3343
The best way, I believe, would be to use a File.Exists
before you try to create the FileStream. Example:
if (File.Exists(path))
{
//Handle existing file
}
else
{
FileStream newFile = new FileStream(path, FileMode.CreateNew);
//Logic to do with your new file
}
Trying to parse the IOException to make sure it's exactly the 'right' IOException is brittle. I believe the only way to do it is compare the IOException's comment or description.
Upvotes: 0
Reputation: 10327
I think the File.Exists method is the most elegant. You can play around with reflection to try and guess the root cause but it's not worth it. It's possible that InnerException is set to something more distinct. Is it null?
And the Message property should describe (in English or whatever language you're using) what exactly happened. Relying on the string returned by Message also isn't a good idea.
I like your idea best to be honest.
Upvotes: 0
Reputation: 1924
I would recommend the other way around: do File.Exist first, then catch the exception. That way you're sure that the exception is not raised by the fact that the file already exists.
Upvotes: 0