0

我最近写了一些与菜单条相关的代码,有一个选项包含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

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

4

2 回答 2

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 更有经验的海报,如果这真的是看起来的那样

于 2013-10-31T22:05:58.517 回答
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

于 2013-10-31T22:30:42.057 回答