Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut files to clipboard in C#

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?

like image 400
friederbluemle Avatar asked Jan 16 '10 16:01

friederbluemle


3 Answers

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);
like image 91
Dark Falcon Avatar answered Nov 01 '22 09:11

Dark Falcon


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.

like image 2
Keith Avatar answered Nov 01 '22 09:11

Keith


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);
    }
}
like image 2
Ronnie Overby Avatar answered Nov 01 '22 10:11

Ronnie Overby