2013-10-31 73 views
0

我最近寫了一些與菜單條相關的代碼,有一個選項包含OpenFile,SaveFile和Exit等。以下是代碼。SaveFileDialog.OpenFile()IndexOutofRangeException

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 

另一個代碼塊完全相同,但withou如果聲明,如下,

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語句?有沒有任何方法可以顯示對話窗口?任何人都可以給我這個索引錯誤信息的線索?謝謝!

+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];,但如果你不顯示該對話框或選擇一個文件名保存這個內部數組可能是空的。

我試圖在財產文件名指標零閱讀的項目,我也得到了同樣的錯誤

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

我想從我們的WinForms聽到更多有經驗的海報,如果這是真的什麼,似乎

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

相關問題