[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Copy files to the clipboard in C#

[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)) 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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.