问题
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