我最近写了一些与菜单条相关的代码,有一个选项包含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 语句的情况下修复它?有什么方法可以显示对话框窗口吗?任何人都可以给我这个索引错误消息的线索吗?谢谢!