复制文件并更改名称

Copy a file and change the name

我被要求制作一个文件复制器,通过添加“_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";          
}

您将 _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);

您可以使用 类 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);