RamHS
RamHS

Reputation: 770

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?

Upvotes: 2

Views: 11372

Answers (2)

hungrycoder
hungrycoder

Reputation: 507

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

Upvotes: 5

Albert
Albert

Reputation: 127

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.

Upvotes: 0

Related Questions