C# FileInfo.MoveTo Cannot create a file when that file already exists exception

This was one of those irritating errors that you get when you're trying to do something quickly before you go home and you can't for the life of you fathom the issue.

I had the following code (simple enough):

FileInfo f = new FileInfo("##File'sPath"); try{...}{     f.MoveTo("##DROPOFFDIRECTORY##")); }catch (Exception e) {...}{ //Logtheexceptionhere}

The fix was simple, you just have to remember to specify the new filename too. (DOH!). Here's the "correct" code.

FileInfo f = new FileInfo("## File's Path"); try{...}{     f.MoveTo(Path.Combine("## DROP OFF DIRECTORY ##", f.Name)); }catch (Exception e) {...}{ //Log the exception here}

Hope that helps you out ;)

Subscribe to TSD

Don’t miss out on the latest posts. Sign up now to get access to the library of members-only posts.
jamie@example.com
Subscribe