Search code examples
c#movefile-rename

How to Move File and Rename it in C#, after receiving it from the server?


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?


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