首页 > 解决方案 > C#如何复制保存在变量中的文件并将其粘贴到不同的位置?

问题描述

目标:

我正在尝试复制存储在变量中的文件..,然后将其粘贴到指定的另一个文件夹中。

我看过这里:https ://stackoverflow.com/a/53731042/12129150但这没有帮助,因为我在变量中有一条路径。

这是我尝试过的:

// File path attached
private string filePath = null;

private void button2_Click(object sender, EventArgs e)
{
    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        openFileDialog.InitialDirectory = "c:\\";
        openFileDialog.Filter = "All Files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;

        openFileDialog.RestoreDirectory = true;

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            //Get the path of specified file
            filePath = openFileDialog.FileName;
        }
    }
}



private void button1_Click(object sender, EventArgs e)
{
    File.Copy(filePath, @"C:\Users\user\Desktop\@filePath");
}

但这只是将其保存到桌面@filePath

标签: c#

解决方案


自行获取文件名

private void button1_Click(object sender, EventArgs e)
{
    var fileName = Path.GetFileName(filePath);
    var newPath = Path.Combine(@"C:\Users\user\Desktop", fileName);
    File.Copy(filePath, newPath);
}

推荐阅读