How to copy a file to another path?

后端 未结 9 1013
长发绾君心
长发绾君心 2020-11-27 04:59

I need to copy a file to another path, leaving the original where it is.

I also want to be able to rename the file.

Will FileInfo\'s CopyTo method work?

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 05:28

    I tried to copy an xml file from one location to another. Here is my code:

    public void SaveStockInfoToAnotherFile()
    {
        string sourcePath = @"C:\inetpub\wwwroot";
        string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
        string sourceFileName = "startingStock.xml";
        string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
        string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
        string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
    
        if (!System.IO.Directory.Exists(destinationPath))
           {
             System.IO.Directory.CreateDirectory(destinationPath);
           }
        System.IO.File.Copy(sourceFile, destinationFile, true);
    }
    

    Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.

提交回复
热议问题