简体   繁体   中英

Command to copy a file to another directory?

I do this code to copy a file to another destination, but i need the his name ( to the copied file) with the date and hour of my PC ... what's wrong ??

string fileToCopy = "d:\\pst\\2015.pst";
string destinationDirectory ="C:\\Users\\pierr_000\\Desktop\\New folder (3)\\ba-{0:MM-DD_hh-mm}.pst";

File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy)); 

It's not working because destinationDirectory is referring to a file. Use Path.GetDirectoryName to retrieve the actual directory and Path.Combine to combine paths.

 File.Copy(fileToCopy, Path.Combine(Path.GetDirectoryName(String.Format(destinationDirectory, DateTime.Now)), Path.GetFileName(fileToCopy))); 

There are a number of issues with your code.

  1. Your format string is incorrect. The day of month is represented by dd not DD .
  2. You aren't using your format string in any meaningful way.
  3. You are concatenating strings rather that using System.IO.Path to construct paths.

It looks like you're trying to do the following:

string fileToCopy = @"d:\pst\2015.pst";
string destinationDirectoryTemplate =
    @"C:\Users\pierr_000\Desktop\New folder (3)\ba-{0:MM-dd_hh-mm}";
var dirPath = string.Format(destinationDirectoryTemplate, DateTime.UtcNow);
var di = new DirectoryInfo(dirPath);
if(!di.Exists)
{
    di.Create();
}
var fileName = Path.GetFileName(fileToCopy);
var targetFilePath = Path.Combine(dirPath, fileName);
File.Copy(fileToCopy, targetFilePath); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM