从服务器接收文件后如何移动文件并在C#中重命名?

Ram*_*mHS 2 c# move file-rename

我正在尝试移动和重命名我从TCP服务器收到的文件.

我的移动和重命名代码:

 *//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";
Run Code Online (Sandbox Code Playgroud)

收到文件后我这样做:

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

但是当它达到时,总是抛出异常"无法完成" File.Move(myServerfile, myfile1);

我试过这个: Console.WriteLine(ex.ToString());

结果: System.IO.IOException:无法创建已存在的文件.

在此输入图像描述

我究竟做错了什么?

hun*_*der 5

好像你已经在目标文件夹中有JobStart.txt文件.

您可以尝试检查它是否存在,然后尝试替换或删除该文件,然后移动.

if (File.Exists(myFile))
{
    File.Delete(myFile);
}
File.Move(myServerfile, myFile);
Run Code Online (Sandbox Code Playgroud)