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