17

I'm looking for a way to programmatically cut a file to the clipboard, for example, some call to a function in C# that does the same as selecting a file in the Windows Explorer and pressing Ctrl + X.

After running the program and pressing Ctrl + V in some other folder on the hard drive, the original file would be moved to the new folder. By looking at Stack Overflow question Copy files to clipboard in C#, I know that it's easy to do the copy job, but cutting seems to work different. How can I do this?

Community
  • 1
  • 1
friederbluemle
  • 33,549
  • 14
  • 108
  • 109

3 Answers3

23

Please try the following, translated from The Code Project article Setting the Clipboard File DropList with DropEffect in VB.NET:

byte[] moveEffect = new byte[] {2, 0, 0, 0};
MemoryStream dropEffect = new MemoryStream();
dropEffect.Write(moveEffect, 0, moveEffect.Length);

DataObject data = new DataObject();
data.SetFileDropList(files);
data.SetData("Preferred DropEffect", dropEffect);

Clipboard.Clear();
Clipboard.SetDataObject(data, true);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
2

Just to see what happens, I replaced the MemoryStream with a DragDropEffects like this:

data.SetData("FileDrop", files);
data.SetData("Preferred DropEffect", DragDropEffects.Move);

Apparently, it works as a genuine cut rather than a copy! (This was on Windows 7 - I have not tried other operating systems). Unfortunately, it works only coincidentally. For example,

data.SetData("Preferred DropEffect", DragDropEffects.Copy);

does not yield a copy (still a cut). It seems that a non-null causes a cut, a null a copy.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Keith
  • 21
  • 2
2

I like to wrap code like this in an API that makes sense. I also like to avoid magic strings of bytes where I can.

I came up with this extension method that solves the mystery that @Keith was facing in his answer, effectively using the DragDropEffects enum.

public static class Extensions
{
    public static void PutFilesOnClipboard(this IEnumerable<FileSystemInfo> filesAndFolders, bool moveFilesOnPaste = false)
    {
        var dropEffect = moveFilesOnPaste ? DragDropEffects.Move : DragDropEffects.Copy;

        var droplist = new StringCollection();
        droplist.AddRange(filesAndFolders.Select(x=>x.FullName).ToArray());     

        var data = new DataObject();
        data.SetFileDropList(droplist);
        data.SetData("Preferred Dropeffect", new MemoryStream(BitConverter.GetBytes((int)dropEffect)));
        Clipboard.SetDataObject(data);
    }
}
Ronnie Overby
  • 45,287
  • 73
  • 267
  • 346