在 Debug模式下,运行C#WinFOrms App时,通过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)
{
}
谢谢!
最佳答案
您正在做的事情似乎没有多大意义。以下几行应该做什么?
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是完整路径,因此将其附加到temp路径将导致无效路径。另外,请考虑使用
Path.Combine
组合两个路径:Path.Combine(tempFolder, Path.GetFileName(FileName))
关于c# - C#WinForms-OpenFileDialog MultiSelect : “Index was outside the bounds of the array.” 上的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489121/