【问题标题】:Command to copy a file to another, user-chosen directory?将文件复制到另一个用户选择的目录的命令?
【发布时间】:2015-11-26 22:41:10
【问题描述】:

我有这段代码可以将文件复制到另一个目标,但是我需要用户选择目标加上复制的文件的名称是 = 旧名称以及我的 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);

【问题讨论】:

  • 抱歉,我不知道如何修复 image 的代码格式错误。
  • 请将代码复制/粘贴到您的帖子中(以便其他人可以将其粘贴到自己的编辑器中进行更改),并描述您尝试运行此代码时发生的情况。
  • 字符串文件复制 = @"d:\pst\2015.pst";字符串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);
  • 不,我需要字符串destinationDirectoryTemplate在文本框中得到他的完整路径

标签: c# file


【解决方案1】:

这应该可以工作

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

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 2021-06-07
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2012-02-09
    • 2012-02-15
    相关资源
    最近更新 更多