Gabriel Apostol
Gabriel Apostol

Reputation: 73

C# File Copy and Paste

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

Upvotes: 0

Views: 1132

Answers (1)

M.Mahdipour
M.Mahdipour

Reputation: 603

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

Upvotes: 3

Related Questions