Question

I am trying to move&rename a file which i received from my TCPserver.

My code for moving and renaming:

 *//My sourcePath*
 static string myServerfile = @"C:\Users\me\Documents\file_client\bin\Debug\test1.txt";
 *//My destinationPath*
 static string myFile = @"C:\test\inbox\JobStart.txt";

After receiving the file I do this:

          fs.Close ();
          serverStream.Close ();
                File.Move(myServerfile, myFile);
                Console.WriteLine("Moved");
            } 
            catch (Exception ex) 
            {
                Console.WriteLine ("Cannot be DONE!");  
            }

But it allways throws exception "Cannot be done" when it reaches File.Move(myServerfile, myfile1);

I tried this: Console.WriteLine(ex.ToString());

Result: System.IO.IOException: A file that already exists, can not be created.

enter image description here

What am i doing wrong?

Was it helpful?

Solution

Seems like you already have had JobStart.txt file in the destination folder.

You may try to check whether it exists and then try to replace or delete that file and then move.

if (File.Exists(myFile))
{
    File.Delete(myFile);
}
File.Move(myServerfile, myFile);

OTHER TIPS

Try:

File.Move(@"C:\SAM.txt", @"C:\New Folder\SAM_newName.txt");

If successful, the first file will no longer exist. If unsuccessful, the operation will be terminated—nothing will be changed on disk. I recommend using this with a try, catch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top