0121 31 45 374
Qoute Icon

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

Tim

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's Path ");
try
{
    f.MoveTo("## DROP OFF DIRECTORY ##"));
}
catch (Exception e)
{
    //Log the exception here
}

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 ;)

Liked this post? Got a suggestion? Leave a comment