C# File Copy and Paste

社会主义新天地 提交于 2021-01-29 19:19:02

问题


I am currently working with Copy and Paste with Item (file name) in Listbox. There's no error but copy and paste seems to not be working. I am new to this so I don't know what is the problem here, any help would be appreciated.

Code in Copy

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

Code in Paste

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

回答1:


In the Paste code, the Paste operation is done only when the target file exists! Please change your code:

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


来源:https://stackoverflow.com/questions/53730904/c-sharp-file-copy-and-paste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!