0

我有一个ListView显示计算机文件和文件夹的文件。I have added a context menu that, when right clicked, it can copy/paste/delete/rename etc. When the file is selected its path is saved in a string.

现在我该如何剪切并保存到剪贴板。然后转到一个目录并将文件粘贴到那里。复制和移动到方法似乎不起作用,因为我必须在单独的点击上实现复制和粘贴

 private void copyToolStripMenuItem_Click(object sender, EventArgs e)
 {
     string ItemClicked = listView1.FocusedItem.Tag.ToString();
     if (ItemClicked != string.Empty)
     {
         Clipboard.SetFileDropList(ItemClicked);//error
     }
}
4

1 回答 1

2

您需要传入 a StringCollectionnot a string。尝试这个:

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count > 0)
    {
        System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
        sc.Add(listView1.FocusedItem.Tag.ToString());

        Clipboard.SetFileDropList(sc);
    }
}

但请注意,这只会复制到剪贴板。为了像您想要的那样剪切,您需要确定这意味着什么:listview从原始位置删除或从其原始位置删除文件(粘贴后?)


回应评论:

//public variables
StringCollection copiedFiles = new StringCollection();
bool cutWasSelected;

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
    CopySelectedFiles();
    cutWasSelected = false;
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
    CopySelectedFiles();
    cutWasSelected = true;
}
private void CopySelectedFiles()
{
    if (listView1.SelectedItems.Count > 0)
    {
        foreach (ListViewItem item in listView1.SelectedItems)
        {
            copiedFiles.Add(item.Tag.ToString());
        }
    }
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
    string destinationFolder;//however you select this
    PasteCopiedFiles(destinationFolder, cutWasSelected);

}

private void PasteCopiedFiles(string DestinationFolder, bool deleteSourceFiles)
{
    if (copiedFiles.Count > 0)
    {
        foreach (string file in copiedFiles)
        {
            if (deleteSourceFiles)
            {
                File.Move(file,Path.Combine(new string[]{DestinationFolder,Path.GetFileName(file)}));
            }
            else
            {
                File.Copy(file, Path.Combine(new string[] { DestinationFolder, Path.GetFileName(file) }));
            }
        }
    }
}
于 2013-01-17T14:07:17.807 回答