1

Hey so lately i've been trying to move files from one folder to another but errors keep coming up. Both the loacation and destination folders are created, location has few .txt files

Here's what i've tried:

string path = @"C:\TESTmove\path";
string path2 = @"C:\TESTmove\destiny";

if (Directory.Exists (path)) 
{
    foreach (string filename in Directory.GetFiles(path)) 
    {
        File.Move (filename, path2);
        //Console.WriteLine (filename);
    }
}
else
{
    Console.WriteLine("Wrong place");
}

and I'm getting this error:

Cannot create a file when that file already exists.

Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
  • What part of the error message don't you understand? – SLaks Sep 25 '15 at 15:21
  • Have you checked that the file does not exist in the destination before moving it? – Ric Sep 25 '15 at 15:21
  • 2
    The second parameter in `File.Move` should be the full path including filename, not just the destination directory. – Jason P Sep 25 '15 at 15:21
  • @WalterWhite For examples of lots of file/directory operations have a read of https://msdn.microsoft.com/en-us/library/vstudio/cc148994%28v=vs.100%29.aspx – Paul Zahra Sep 25 '15 at 15:23
  • There are not files in the "destiny" folder. i dont want to overwrite anything, just need to move the files in a folder "from a to b" – Mister White Sep 25 '15 at 15:25

2 Answers2

0

You're creating the same file named "destiny" in the directory path "C:\TESTmove". (That's not what you want, but that's basically what the code you posted is going to do.)

Instead, include the filename when moving the file to the new location.

File.Move(filename, Path.Combine(path2, Path.GetFileName(filename)));
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

Your code is wrong, you are saying:

string path2 = @"C:\TESTmove\destiny";
string filename = @"C:\TESTmove\path\test1.txt";

File.Move (filename, path2);

path2 should contain the path and the filename.

e.g. It should be like so

string sourceFile = @"C:\TESTmove\path\whatever.txt";
string destinationFile = @"C:\TESTmove\whatever.txt";

System.IO.File.Move(sourceFile, destinationFile);

There is no magic involved, File.Move needs to know what file you are moving to what file (not just location).

Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
  • Directory.GetFiles() gives the whole path of the files e.g. when printing "filename" the output is: C:\TESTmove\path\test1.txt – Mister White Sep 25 '15 at 15:35