Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.Move Does Not Work - File Already Exists

Tags:

c#

file-io

I've got a folder:

c:\test

I'm trying this code:

File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test"); 

I get exception:

File already exists

The output directory definitely exists and the input file is there.

like image 977
Jack Kada Avatar asked May 07 '11 12:05

Jack Kada


People also ask

How do you handle a file already exists?

This error has the following causes and solutions: This error occurs at run time when the new file name, for example, one specified in a Name statement, is identical to a file name that already exists. Specify a new file name in the Name statement or delete the old file before specifying it in a Name statement.

Does file move overwrite?

File. Move() doesn't support overwriting of an existing file. In fact, it will throw an IOException if a file with the same path as sourceDestFilename already exists.

Can not create a file when that file already exists?

This is because you're trying to fake the existence of the Backup folder (so it must not exist already), but you also need its parents to exist. Windows will hence create a hard link shortcut Backup on the C:\ drive.

How do I move a file in C#?

Move() is an inbuilt File class method that is used to move a specified file to a new location. This method also provides the option to specify a new file name. Syntax: public static void Move (string sourceFileName, string destFileName);


2 Answers

What you need is:

if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {     File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt"); } 

or

if (File.Exists(@"c:\test\Test\SomeFile.txt")) {     File.Delete(@"c:\test\Test\SomeFile.txt"); } File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt"); 

This will either:

  • If the file doesn't exist at the destination location, successfully move the file, or;
  • If the file does exist at the destination location, delete it, then move the file.

Edit: I should clarify my answer, even though it's the most upvoted! The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires. So, your second parameter should be c:\test\Test\SomeFile.txt.

like image 179
Jamie Howarth Avatar answered Sep 28 '22 03:09

Jamie Howarth


You need to move it to another file (rather than a folder), this can also be used to rename.

Move:

File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt"); 

Rename:

File.Move(@"c:\test\SomeFile.txt", @"c:\test\SomeFile2.txt"); 

The reason it says "File already exists" in your example, is because C:\test\Test tries to create a file Test without an extension, but cannot do so as a folder already exists with the same name.

like image 30
Lee Avatar answered Sep 28 '22 04:09

Lee