2

I'm developing a WinForms application using C# with an OpenFileDialog and FileBrowserDialog and I'd like to:

  1. Enable selection of multiple xls files.
  2. After selection is made, Display selected xlsx filenames in textbox
  3. Copy the selected files to a separate directory Consolidated

How can I accomplish this?

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
Brian McCarthy
  • 4,658
  • 16
  • 49
  • 66

3 Answers3

13

Here is sample code:

        OpenFileDialog od = new OpenFileDialog();
        od.Filter = "XLS files|*.xls";
        od.Multiselect = true;
        if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string tempFolder = System.IO.Path.GetTempPath();

            foreach (string fileName in od.FileNames)
            {
                System.IO.File.Copy(fileName, tempFolder + @"\" + System.IO.Path.GetFileName(fileName));
            }
        }
Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
  • @AntonSemenov, thanks for the response! Wouldn't this be used on a web application vs a win forms application? There's no methods in here or selectFilesButton_Click method. – Brian McCarthy Mar 17 '11 at 13:02
  • @AntonSemenov, This code is good but doesn't really give me the complete picture. Where would this code go into the application? Under the private void selectFilesButton_Click method? Would I have to edit any other methods? – Brian McCarthy Mar 18 '11 at 13:15
  • Ok. Create new Windows Forms Application project and put button on form. Double click on button, after that IDE will create button click event handler. Just put code from my answer in button click event handler and run project – Anton Semenov Mar 18 '11 at 16:52
  • @AntonSemenov, +1 thanks for your help. Whats the difference between using an if/else combo and a try/catch combo? I combined your answers to come up w my answer. Please check out my answer and see if it looks good to you. – Brian McCarthy Mar 24 '11 at 13:41
  • Your solution is OK. But one remark. There is no sence in usage `try` block without corresponding `catch` block. In this case exception would be catched on application level. I would prefer to add corresponding `catch` block and add log message inside it. The difference between if/else and try/catch is great. Actually they have different sence. The First one is for algorithm path selection and second one is for exclusive situation processing. Such situations often is not a part of algorithm and in catch block you just catch cases wich was not planed in algorythm but hapened in some conditions. – Anton Semenov Mar 24 '11 at 14:20
  • To be more familiar with try/catch you may check out this link http://msdn.microsoft.com/en-us/library/0yd65esw.aspx – Anton Semenov Mar 24 '11 at 14:29
8

There is MultiSelect property of OpenFileDialog which you need to set to true to allow selecting multiple files.

Here is a code example from MSDN which allows the user to select a multiple number of images and display them in PictureBox controls on a Form:

private void Form1_Load(object sender, EventArgs e)
{
  InitializeOpenFileDialog();
}

private void InitializeOpenFileDialog()
{
  // Set the file dialog to filter for graphics files.
  this.openFileDialog1.Filter =
    "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
    "All files (*.*)|*.*";

  // Allow the user to select multiple images.
  this.openFileDialog1.Multiselect = true;
  this.openFileDialog1.Title = "My Image Browser";
}

private void selectFilesButton_Click(object sender, EventArgs e)
{
  DialogResult dr = this.openFileDialog1.ShowDialog();
  if (dr == System.Windows.Forms.DialogResult.OK)
  {
    // Read the files
    foreach (String file in openFileDialog1.FileNames) 
    {
        // Create a PictureBox.
        try
        {
            PictureBox pb = new PictureBox();
            Image loadedImage = Image.FromFile(file);
            pb.Height = loadedImage.Height;
            pb.Width = loadedImage.Width;
            pb.Image = loadedImage;
            flowLayoutPanel1.Controls.Add(pb);
        }
        catch (SecurityException ex)
        {
            // The user lacks appropriate permissions to read files, discover paths, etc.
            MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                "Error message: " + ex.Message + "\n\n" +
                "Details (send to Support):\n\n" + ex.StackTrace
            );
        }
        catch (Exception ex)
        {
            // Could not load the image - probably related to Windows file system permissions.
            MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                + ". You may not have permission to read the file, or " +
                "it may be corrupt.\n\nReported error: " + ex.Message);
        }
    }
}
Community
  • 1
  • 1
Lav
  • 1,850
  • 15
  • 17
  • thanks for your response! The code example allows the user to select a multiple number of images and display them in PictureBox controls on a Form. How would I have the selected xls files copied to the Consolidated folder and converted to .csv files via the command prompt command [C:\CommissionRecon\ConvertExcel\ConvertExcelTo.exe ^ xxxxx.xls ^ xxxx.csv] – Brian McCarthy Mar 17 '11 at 12:58
  • would something like this work: foreach (string fileName in od.FileNames) { System.IO.File.Copy(fileName, consolidatedFolder + @"\" + System.IO.Path.GetFileName(fileName)); } – Brian McCarthy Mar 17 '11 at 13:39
  • +1 thanks for your help. Whats the difference between using an if/else combo and a try/catch combo? I combined your answers to come up w my answer. Please check out my answer and see if it looks good to you. – Brian McCarthy Mar 24 '11 at 13:42
1

Combining both answers, here's the code I came up with to:

  • Enabling the user to Select Multiple XLSX Files (using MultiSelect, OpenFileDialog, this.OpenFileDialog Properties & FileBrowserDialog)
  • After selection is made, Display Selected XLSX Filenames in Textbox (by setting textBoxSourceFiles.Text value to sourceFileOpenFileDialog.FileNames)
  • Copy the Selected Files to a separate Consolidated directory (using foreach loop, System.IO.File.Copy, System.IO.Path.GetFileName, sourceFileOpenFileDialog.FileName)

    private void sourceFiles_Click(object sender, EventArgs e)
    {
        Stream myStream;
        OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
    
        this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
        this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
        this.sourceFileOpenFileDialog.FilterIndex = 2;
        this.sourceFileOpenFileDialog.RestoreDirectory = true;
        this.sourceFileOpenFileDialog.Multiselect = true;
        this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
    
        if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        // populates text box with selected filenames 
                        textBoxSourceFiles.Text = sourceFileOpenFileDialog.FileNames; 
                    }
                }       // ends if 
            }           // ends try 
    
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }              // ends if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
    }                  // ends public void sourceFiles_Click
    
    private void consolidateButton_Execute_Click(object sender, EventArgs e)
    {
    
        string consolidatedFolder = targetFolderBrowserDialog.SelectedPath; 
    
            foreach (String file in sourceFileOpenFileDialog.FileNames)
            {
                try
                {
                    // Copy each selected xlsx files into the specified TargetFolder 
    
                    System.IO.File.Copy(sourceFileOpenFileDialog.FileName, consolidatedFolder + @"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
                    Log("File" + sourceFileOpenFileDialog.FileName + " has been copied to " + consolidatedFolder + @"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
                }  
            }          // ends foreach loop
    }                  // ends void consolidateButton_Execute_Click
    
Brian McCarthy
  • 4,658
  • 16
  • 49
  • 66
  • You want the files to copy only when the consolidateButton is clicked not once theyre selected so the file.copy operation had to be moved under the consolidateButton_Execute_Click method :) – Brian McCarthy Mar 24 '11 at 13:58