Select & copy multiple files

We are going to create an application in which we'll select multiple files by "OpenFileDialog" and copy those files to specific directory.
  • Open visual studio and create new "Windows Form Application" project.
  • Go to Toolbox and drag a button.
  • Change name of button to "FileUploadBtn".
  • Change text of button to "Upload Files".
  • Now double click at that button and add following code in its click event.

private void FileUploadBtn_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();

    //Add filter, if you want to allow all extenssions just remove it.
    openFileDialog.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";

    // Set multiselect true for slecting multiple files
    openFileDialog.Multiselect = true;
          
    // Show open file dialog and check if Open button is pressed.
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        // Set directory name and create it.
        string directory = "Files";

        Directory.CreateDirectory(directory);

        // Read all files.
        foreach (string fileName in openFileDialog.FileNames)
        {
            // Get file name without its path.
            string fn = System.IO.Path.GetFileName(fileName);

            // Copy file to specific directory.
            File.Copy(fileName, directory + "/" + fn, true);
        }
    }
}

Now run the application and test it. It will create a directory named "Files" to your application's "bin/Debug"directory and copy files in that new created directory.
"File.Copy" function is used for copying a file. As you can see in above code that its 3rd parameter is true. Actually it is for setting the overwrite property true. Means if file is already exist in destination directory it will overwrite it.

Comments

Popular posts from this blog

Add button & its click event programmatically in C#

Add images in ListView (C#)

Resize and Save Multiple Images in C#