【问题标题】:C# Windows Forms - Select and Copy Multiple Files w MultiSelect, OpenFileDialog, & FileBrowserDialogC# Windows 窗体 - 使用 Multi Select、OpenFileDialog 和 FolderBrowserDialog 选择和复制多个文件
【发布时间】:2011-07-16 22:08:55
【问题描述】:

我正在使用带有 OpenFileDialog 和 FileBrowserDialog 的 C# 开发 WinForms 应用程序,我想:

  1. 启用选择多个 xls 文件。
  2. 选择后,在文本框中显示选定的 xlsx 文件名
  3. 将选定的文件复制到单独的目录合并

我怎样才能做到这一点?

【问题讨论】:

    标签: c# openfiledialog multi-select .net file-browser


    【解决方案1】:

    OpenFileDialogMultiSelect 属性需要设置为 true 以允许选择多个文件。

    Here is a code example 来自 MSDN,它允许用户选择多个图像并将它们显示在窗体上的 PictureBox 控件中:

    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);
            }
        }
    }
    

    【讨论】:

    • 感谢您的回复!该代码示例允许用户选择多个图像并将它们显示在窗体上的 PictureBox 控件中。如何将选定的 xls 文件复制到 Consolidated 文件夹并通过命令提示符命令 [C:\CommissionRecon\ConvertExcel\ConvertExcelTo.exe ^ xxxxx.xls ^ xxxx.csv] 转换为 .csv 文件
    • 会有这样的工作:foreach(od.FileNames 中的字符串文件名){ System.IO.File.Copy(fileName,solidatedFolder + @"\" + System.IO.Path.GetFileName(fileName )); }
    • +1 感谢您的帮助。使用 if/else 组合和 try/catch 组合有什么区别?我结合了你的答案来得出我的答案。请查看我的回答,看看它是否适合您。
    【解决方案2】:

    这里是示例代码:

            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));
                }
            }
    

    【讨论】:

    • @AntonSemenov,感谢您的回复!这不会在 Web 应用程序和 win 表单应用程序上使用吗?这里没有方法或 selectFilesButton_Click 方法。
    • @AntonSemenov,这段代码很好,但并没有真正给我完整的画面。这段代码将在哪里进入应用程序?在私有 void selectFilesButton_Click 方法下?我是否需要编辑任何其他方法?
    • 好的。创建新的 Windows 窗体应用程序项目并将按钮放在窗体上。双击按钮,IDE 将创建按钮单击事件处理程序。只需将我的答案中的代码放入按钮单击事件处理程序并运行项目
    • @AntonSemenov,+1 感谢您的帮助。使用 if/else 组合和 try/catch 组合有什么区别?我结合了你的答案来得出我的答案。请查看我的回答,看看它是否适合您。
    • 您的解决方案没问题。但要说一句。如果没有对应的catch 块,使用try 块是没有意义的。在这种情况下,将在应用程序级别捕获异常。我宁愿添加相应的catch 块并在其中添加日志消息。 if/else 和 try/catch 之间的区别很大。其实他们有不同的感觉。第一个用于算法路径选择,第二个用于排他情况处理。这种情况通常不是算法的一部分,并且在 catch 块中,您只是捕获未在算法中计划但在某些情况下发生的情况。
    【解决方案3】:

    结合这两个答案,这是我想出的代码:

    • 使用户能够选择多个 XLSX 文件(使用 MultiSelect、OpenFileDialog、this.OpenFileDialog Properties 和 FileBrowserDialog)
    • 选择后,在文本框中显示选定的 XLSX 文件名(通过将 textBoxSourceFiles.Text 值设置为 sourceFileOpenFileDialog.FileNames)
    • 将所选文件复制到单独的合并目录(使用 foreach 循环、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
      

    【讨论】:

    • 您希望文件仅在单击合并按钮时才复制,而不是在选择它们后复制,因此必须在 consolidateButton_Execute_Click 方法下移动 file.copy 操作:)
    猜你喜欢
    • 2014-08-08
    • 1970-01-01
    • 2013-09-21
    • 2012-07-22
    • 2011-01-15
    • 1970-01-01
    • 2016-09-28
    • 2014-08-18
    相关资源
    最近更新 更多