【问题标题】:Copy a file and change the name复制文件并更改名称
【发布时间】:2016-12-14 11:09:04
【问题描述】:

我被要求制作一个文件复制器,它会通过添加“_Copy”来更改文件的名称,但会保留文件的类型。

例如:

c:\...mike.jpg

到:

c:\...mike_Copy.jpg

这是我的代码:

private void btnChseFile_Click(object sender, EventArgs e)
{
    prgrssBar.Minimum = 0;
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Title = "Which file do you want to copy ?";            

    DialogResult fc = ofd.ShowDialog();                       
    tbSource.Text = ofd.FileName;
    tbDestination.Text = tbSource.Text + "_Copy";          
}

【问题讨论】:

  • 问题/错误是什么?
  • @Bas 很明显。 “没用”

标签: c# winforms openfiledialog


【解决方案1】:

您可以使用 System.IO.FileInfoSystem.IO.Path 类来执行您正在尝试的操作:

OpenFileDialog od = new OpenFileDialog();
if(od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName);
    string oldFile = fi.FullName;

    string newFile = oldFile.Replace(System.IO.Path.GetFileNameWithoutExtension(oldFile), 
        string.Format("{0}_Copy", 
            System.IO.Path.GetFileNameWithoutExtension(oldFile)));
    MessageBox.Show(newFile);
}

然后你可以调用下面的来执行复制:

System.IO.File.Copy(oldFile, newFile);

【讨论】:

    【解决方案2】:

    您将_Copy 附加到文件名的末尾而不是扩展名之前。您需要在扩展之前添加它:

    string destFileName = $"{Path.GetFileNameWithoutExtension(ofd.FileName)}_Copy{Path.GetExtension(ofd.FileName)}";
    

    或者没有 C# 6:

    string destFileName = String.Format("{0}_Copy{1}",
                                        Path.GetFileNameWithoutExtension(ofd.FileName),
                                        Path.GetExtension(ofd.FileName));
    

    然后获取文件的完整路径:

    string fullPath = Path.Combine(Path.GetDirectoryName(ofd.FileName, destFileName));
    

    然后执行实际复制只需使用:

    File.Copy(ofd.FileName, fullPath);
    

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多