An exception is thrown in C # for the FileStream constructor with CreateNew for an existing file

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

It seems like you need to create a FileStream with a set of FileMode.CreateNew. In fact, it throws an exception if the file exists.

But how do you know this exception unlike other possible exceptions created by file creation? The documentation at http://msdn.microsoft.com/en-us/library/47ek66wy.aspx lists this case as an "IOException", which is explicitly vague as other things can cause this.

Is the answer here that I break an IOException and then just do File.Exists?

+4
source share
4 answers

You can get the error code from the exception as follows:

int hr = Marshal.GetHRForException( ex ); 

There is 0x80070050 for the file.

+5
source

I would recommend otherwise: make File.Exist first, then catch the exception. Thus, you are sure that the exception is not related to the fact that the file already exists.

0
source

I think the File.Exists method is the most elegant. You can play with reflection to try and guess the root cause, but it's not worth it. It is possible that InnerException is set to something clearer. Is it null?

And the Message property should describe (in English or any other language that you use) what exactly happened. Relying on the string returned by Message is not a good idea.

I like your idea to be honest.

0
source

The best way, I suppose, is to use File.Exists before trying to create a 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 an IOException to make sure that the β€œcorrect” IOException is fragile. I believe the only way to do this is to compare a comment or description of an IOException.

0
source

Source: https://habr.com/ru/post/1395693/


All Articles