Copy files to the clipboard in C#

[copy files]

The example Paste files from the clipboard in C# shows how a program can paste files from the clipboard. You can copy the files to the clipboard by selecting them in Windows Explorer and pressing Ctrl+C.

This example shows how a C# program can use code to copy files to the clipboard.

As you saw in the previous example, a list of files copied to the clipboard is actually an array of file names added to the clipboard with the data type FileDrop. This example simply builds an array of string names and places it in the clipboard, setting its data type to FileDrop.

The following code shows how the program does this.

private void Form1_Load(object sender, EventArgs e)
{
    // Copy some files to the clipboard.
    List<string> file_list = new List<string>();
    foreach (string file_name in
            Directory.GetFiles(Application.StartupPath))
        file_list.Add(file_name);
    Clipboard.Clear();
    Clipboard.SetData(DataFormats.FileDrop, file_list.ToArray());

    // Paste the file list back out of the clipboard.
    string[] file_names = (string[])
        Clipboard.GetData(DataFormats.FileDrop);

    // Display the pasted file names.
    lstFiles.DataSource = file_names;
}

First, the program makes an array of file names. This example makes a List<string> containing the files in the application’s startup directory, but your program can build the array in any way you like.

The code then clears the clipboard’s data and uses the Clipboard object’s SetData method to set the object’s data to the file names (converted into an array). It passes the SetData method the parameter FileDrop so the Clipboard knows this is a list of file names.

Next, to show that the clipboard contains the list of files, the program uses the Clipboard object’s GetData method to retrieve the file names. It sets the ListBox control’s DataSource to the array of file names so you can see them.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in clipboard, interoperability and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *