C#WinForms - OpenFileDialog MultiSelect出错:“索引超出了数组的范围。”

时间:2011-03-30 16:22:19

标签: c# winforms debugging compiler-errors openfiledialog

在调试模式下,在运行C#WinFOrms应用程序时,通过OpenFileDialog选择文件后,我得到了

       Error: Could not read file from disk. 
       Original error: Index was outside the bounds of the array. 

您对如何修复此错误有任何想法吗?

这是我的代码:

    // When the user clicks on Select Files Button, this happens                
    private void sourceFiles_Click(object sender, EventArgs e)
    {
        Stream myStream;
        int i = 0;
        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 (this.sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                string tempFolder = System.IO.Path.GetTempPath();

                foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
                {
                    this.sourceFileOpenFileDialog.FileNames[i] = FileName;
                    listBoxSourceFiles.Items.Add(FileName);
                    Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
                    i++;
                    System.IO.File.Copy(FileName, tempFolder + @"\" + FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }

    }

    //method for the sourcefileOpenFileDialog.  Do I need anything here?
    private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
    {

    }

    //method for the listbox. Do I need anything here? 
    private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

谢谢!

1 个答案:

答案 0 :(得分:3)

你在做什么似乎没有多大意义。以下行应该做什么?

this.sourceFileOpenFileDialog.FileNames[i] = FileName;

只需将您的foreach更改为:

foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
    listBoxSourceFiles.Items.Add(FileName);
    Log("Source Files: " + FileName);
    System.IO.File.Copy(FileName, Path.Combine(tempFolder, Path.GetFileName(FileName)));
}

错误源于这样一个事实:您有两个名为sourceFileOpenFileDialog的变量。一个是您的类的成员,一个在方法内声明。 在方法中声明的那个只在以下行中使用:

Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);

由于此实例未用于向用户显示对话框,因此其FileNames属性的Length为0,因此尝试访问其中的任何项会导致异常。

<强>更新
还有一个问题:
FileName是一个完整路径,因此将其附加到临时路径将导致路径无效。另外,请考虑使用Path.Combine组合两条路径:

Path.Combine(tempFolder, Path.GetFileName(FileName))