Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste files from the clipboard

Thanks to Stack Overflow question Copy files to clipboard in C#, I was able to use Clipboard.SetFileDropList and end up with:

using System;
using System.Collections.Specialized;
using System.Windows.Forms;

class Program
{
    [STAThread]
    static void Main ( string[] args)
    {    
        StringCollection paths = new StringCollection();
        paths.Add( @"C:\Users\Antonio\Desktop\MyDirectory" );
        Clipboard.SetFileDropList( paths);
    }
}

That way I can place an entire directory on the clipboard and paste it where I need it to. I would like to be able to paste it with code though. I don't want to go to the place where I want to paste it and then press Ctrl + V. In other words, I am looking for something like:

Clipboard.Paste("C:\Users\LocationWhereIWantToPasteTheFolder")

I know I can get all the files recursively and then paste them one by one. But why reinvent the wheel? It will be nice if the OS can do it for me...

like image 428
Tono Nam Avatar asked Nov 28 '12 21:11

Tono Nam


1 Answers

The Clipboard has a protocol, a mutually agreed-upon way to get data from one process to another. Such a protocol needs to have limited ways to put sensible data on the clipboard. You can put whatever you want on the clipboard, notably a .NET object. But if the other app that pastes the clipboard data doesn't understand .NET objects, highly likely if it wasn't written in .NET then it is just going to exclaim WTF.

So the method you are using is just a little Clipboard class helper method that puts data on the clipboard using a standard protocol. One that another app is likely to understand, but no guarantee. The protocol is DataFormats.FileDrop.

Your intended replacement will work just fine too, you can certainly put a string on the clipboard. The most basic thing you'd ever want to copy/paste. But the app that pastes it will only recognize it as just a string. It has no clue that the string is supposed to mean something else. The protocol is DataFormats.Text.

The solution is very simple, just write a little private helper method that takes a string. And uses Directory.GetFiles() to create a StringCollection that you put on the clipboard. Simple, mission accomplished, kiss.

like image 118
Hans Passant Avatar answered Sep 20 '22 17:09

Hans Passant