C# 文件复制和粘贴

C# File Copy and Paste

我目前正在使用列表框中的项目(文件名)进行复制和粘贴。没有错误,但复制和粘贴似乎不起作用。我是新手,所以我不知道这里有什么问题,任何帮助将不胜感激。

副本中的代码

 if(lvwExplorer.SelectedItems[0].Text != "" && lvwExplorer.SelectedItems.Count == 1)
        {
            Clipboard.SetText(lvwExplorer.SelectedItems[0].Text);
        }
        else
        {
            MessageBox.Show("You can only copy one element at a time.", "Cannot Copy", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

粘贴代码

string path = Clipboard.GetText();
        char seperator = '\';
        string originalFileName = path.Split(seperator)[path.Split(seperator).Length - 1];
        string target = cbxAddress.Text + "\" + originalFileName;

        try
        {
            if(File.Exists(target))
            {
                if (MessageBox.Show("The File you want to copy already exists. Do you want to replace it?", "File exists", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    File.Delete(target);
                    File.Copy(path, target, false);
                    GoToDirectory();
                }
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show("Error " + ex.Message);
        }
    }

Paste代码中,只有目标文件存在时才会进行Paste操作!请更改您的代码:

            ... 
            if(File.Exists(target))
            {
                if (MessageBox.Show("The File you want to copy already exists. Do you want to replace it?", "File exists", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    File.Delete(target);
                    File.Copy(path, target, false);
                    GoToDirectory();
                }
            }
            else
            {
                File.Copy(path, target, false);
                GoToDirectory();
            }
            ...