C# WinForms 应用程序 - 使用 OpenFileDialog、MultiSelect、日志记录调试错误

发布于 2024-10-26 09:23:37 字数 2798 浏览 6 评论 0原文

背景:我正在使用 C# 和 OpenFileDialog 和 FileBrowserDialog 开发一个 WinForms 应用程序,该应用程序应该:

  1. 启用多个 xls 文件的选择。
  2. 选择后,在文本框中显示选定的 xlsx 文件名
  3. 将选定的文件复制到单独的目录 合并
  4. 在 winForm 应用程序底部的日志记录窗口中显示结果

您建议如何修复调试中的以下错误:

  1. 选择文件后从 FileBrowserDialog 中,出现另一个 FileBrowserDialog 框
  2. 文本框中仅显示所选文件中的 1 个。没有足够的空间来显示所有文件,因为文件路径太长。是否可以只显示文件名而不显示完整路径?除了在您推荐的文本框中显示所选文件之外,是否还有更好的方法来确认 WinForm 中的 MultiSelect 是否有效?
  3. 单击“合并”按钮不会将所选文件复制到合并目录或显示正确的日志文件。
  4. 我在日志窗口中看到以下内容:“源文件:System.String[]”

这是我的代码:

private void sourceFiles_Click(object sender, EventArgs e)
{
    Stream myStream;
    int i = 0;
    OpenFileDialog sourceFilesList = 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)
                {
                     Log("Source Files: " + sourceFilesList.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

对于任何有用的答案,我都会投 +1 票!
感谢您的关注!

更新:更新了带有 foreach(sourceFilesList.FileNames 中的字符串 FileName)循环和列表框控件的代码,文件浏览器加载 2x 时仍然存在问题,并且出现“源文件:System.String[]”消息

Background: I'm developing a WinForms application using C# with an OpenFileDialog and FileBrowserDialog that is supposed 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
  4. Show results in logging window on the bottom of the winForm App

How do you recommend to fix any of the following Errors in Debugging:

  1. After selecting the files from the FileBrowserDialog, another FileBrowserDialog box comes up
  2. Only 1 of the files selected shows up in the textbox. There's not enough room to display all files b/c the file paths are so long. Would it be possible to just display the filename without the full path? Is there a better way for confirming the MultiSelect worked in a WinForm besides displaying the selected files in a textbox that you recommend?
  3. Hitting the Consolidate button does not copy the selected files to the consolidated directory or display the correct log files.
  4. I get the following in the Logging Window: "Source Files: System.String[]"

Here's my code:

private void sourceFiles_Click(object sender, EventArgs e)
{
    Stream myStream;
    int i = 0;
    OpenFileDialog sourceFilesList = 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)
                {
                     Log("Source Files: " + sourceFilesList.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

I will give +1 up-votes for any helpful answers!
Thanks for looking!

Update: Updated code w/ a foreach (string FileName in sourceFilesList.FileNames) loop and a listbox control, still having problems w/ filebrowser loading 2x, and the "Source Files: System.String[]" message

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

春夜浅 2024-11-02 09:23:37

您的代码片段与您的问题不太匹配,没有迹象表明您显示FolderBrowserDialog。 File.Copy() 调用中有一个明显的错误,您传递了 sourceFileOpenFileDialog.FileName 而不是 file

检查此答案,了解在有限空间内显示路径名称的方法:

 using System;
 using System.ComponentModel;
 using System.Windows.Forms;

 class PathLabel : Label 
 {
   [Browsable(false)]
   public override bool AutoSize 
   {
       get { return base.AutoSize; }
       set { base.AutoSize = false; }
   }
   protected override void OnPaint(PaintEventArgs e) 
   {
      TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;
      TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);
   }
}

Your code snippet doesn't match your question very well, there's no sign of you displaying the FolderBrowserDialog. There is an obvious mistake in the File.Copy() call, you pass sourceFileOpenFileDialog.FileName instead of file.

Check this answer for a way to display path names in a limited amount of space:

 using System;
 using System.ComponentModel;
 using System.Windows.Forms;

 class PathLabel : Label 
 {
   [Browsable(false)]
   public override bool AutoSize 
   {
       get { return base.AutoSize; }
       set { base.AutoSize = false; }
   }
   protected override void OnPaint(PaintEventArgs e) 
   {
      TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;
      TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);
   }
}
粉红×色少女 2024-11-02 09:23:37

要仅从文件路径获取文件名,请使用 Path.GetFileName(...)。

要检查是否选择了多个文件,您只需检查 openFileDialog.FileNames Length 属性 - 它是一个数组。

To get only file name from file path use Path.GetFileName(...).

To check if multiple files were selected, you can just check openFileDialog.FileNames Length property - it's an array.

猫烠⑼条掵仅有一顆心 2024-11-02 09:23:37

通过添加修复了记录窗口消息:“源文件:System.String[]”:

                 foreach (string FileName in sourceFilesList.FileNames)
                 {
                    sourceFilesList.FileNames[i] = FileName;
                    listBoxSourceFiles.Items.Add(FileName);
                    Log("Source Files: " + sourceFilesList.FileNames[i]);
                    i++;
                 }

                 // under  if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)  

修复了通过以下方式选择文件时出现的 2 个 FileBrowserDialog 对话框:

     if ((myStream = sourceFilesList.OpenFile()) != null)
     // deleted duplicate line 

Fixed Logging Window Message: "Source Files: System.String[]" by adding:

                 foreach (string FileName in sourceFilesList.FileNames)
                 {
                    sourceFilesList.FileNames[i] = FileName;
                    listBoxSourceFiles.Items.Add(FileName);
                    Log("Source Files: " + sourceFilesList.FileNames[i]);
                    i++;
                 }

                 // under  if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)  

Fixed 2 FileBrowserDialog boxes coming up when Selecting files by:

     if ((myStream = sourceFilesList.OpenFile()) != null)
     // deleted duplicate line 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文