Copy files to the clipboard in C#

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))
    Clipboard.SetData(DataFormats.FileDrop, file_list.ToArray());

    // Paste the file list back out of the clipboard.
    string[] file_names = (string[])

    // 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 way you like.

The code then clears the clipboard's data and uses the Clipboard object's SetData method to set the Clipboard'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's DataSource to the array of file names so you can see them.



What did you think of this article?

  • No trackbacks exist for this post.
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.