SaveFileDialog.OpenFile()IndexOutofRangeException

时间:2013-10-31 21:31:53

标签: vb.net indexoutofboundsexception savefiledialog

我最近写了一些与菜单条带相关的代码,有一个选项包含OpenFile,SaveFile和Exit等。以下是代码。

Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True
    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        Try
            myStream = saveFileDialog1.OpenFile()
            If (myStream IsNot Nothing) Then
                ' Code to write the stream goes here.
                Dim sw As New StreamWriter(myStream)

                sw.Flush()
                sw.Close()

                myStream.Close()
             End If
         Catch Ex As Exception
             MessageBox.Show("Can't save file on disk: " & Ex.Message)
         End Try
    End If

另一块完全相同的代码但是使用If语句,如下所示,

Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True

    Try
        myStream = saveFileDialog1.OpenFile()
        If (myStream IsNot Nothing) Then
            ' Code to write the stream goes here.
            Dim sw As New StreamWriter(myStream)
            'some sw.WriteLine code here...            
            sw.Flush()
            sw.Close()

            myStream.Close()
         End If
     Catch Ex As Exception
         MessageBox.Show("Can't save file on disk: " & Ex.Message)
     End Try

我遇到的问题是第二段代码,当它运行时系统会抛出索引超出范围异常,如何在不使用If语句的情况下修复它?有什么方法可以显示对话框窗口吗?任何人都可以给我这个索引错误消息的线索?谢谢!

2 个答案:

答案 0 :(得分:0)

查看OpenFile的源代码可以发现可能的错误点

public Stream OpenFile()
{
    IntSecurity.FileDialogSaveFile.Demand();
    string str = base.FileNamesInternal[0];
    if (string.IsNullOrEmpty(str))
    {
        throw new ArgumentNullException("FileName");
    }
    Stream stream = null;
    new FileIOPermission(FileIOPermissionAccess.AllAccess, IntSecurity.UnsafeGetFullPath(str)).Assert();
    try
    {
        stream = new FileStream(str, FileMode.Create, FileAccess.ReadWrite);
    }
    finally
    {
        CodeAccessPermission.RevertAssert();
    }
    return stream;
}

似乎代码试图获取base.FileNamesInternal[0];但是如果你没有显示对话框或选择文件名来保存这个内部数组可能是空的。

我试图在属性FileNames中读取索引为零的项目,我得到相同的错误

string file = saveFileDialog1.FileNames(0)  ' Index out of range....

我想听听我们的WinForms更有经验的海报,如果这真的是它看起来

答案 1 :(得分:0)

我想我对你想要完成的事情感到有点困惑。

在第二个例子中,似乎你从未'显示对话框'即saveFileDialog1.ShowDialog()

因此用户无法选择文件/路径

然后尝试使用尚未设置的文件/路径

http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.openfile.aspx

如果你只是需要打开任意文件进行写入而不向用户显示对话框,为什么不使用File.Open()或其他东西?

http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx