简体   繁体   中英

Command to copy a file to another, user-chosen directory?

I have this code to copy a file to another destination, however I need the users to choose the destination plus the name of file copied is = the old name with the date and hour of my PC ..

string fileToCopy = @"d:\pst\2015.pst";
string destinationDirectoryTemplate = textBox2.Text;

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

This should work

protected void Button3_Click(object sender, EventArgs e)
        {
            string fileToCopy = @"e:\TestFile.pdf"; 
            string destinationDirectoryTemplate = TextBox1.Text;
            var dirPath = string.Format(destinationDirectoryTemplate, DateTime.UtcNow);
            var di = new DirectoryInfo(dirPath);
            if (!di.Exists) 
            { di.Create(); } 
            var fileName = Path.GetFileNameWithoutExtension(fileToCopy);
            var extn = Path.GetExtension(fileToCopy);

            var finalname = fileName + " " + string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + extn;
            var targetFilePath = Path.Combine(dirPath, finalname);
            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