2012-06-28 65 views
1

我有一個正在更新日誌信息的富文本框。有一個按鈕可以將日誌輸出保存到文件中。當我使用下面的代碼嘗試將輸出保存到文件時,我收到「進程無法訪問該文件,因爲它正在被另一個進程使用」異常。我不知道爲什麼我收到這個例外。它發生在我在對話框中創建的新文件中。它發生在我嘗試保存信息的任何文件上。C#進程無法訪問文件,因爲它正在被另一個進程使用(文件對話框)

private void saveLog_Click(object sender, EventArgs e) 
{ 
      OnFileDialogOpen(this, new EventArgs()); 
      // Displays a SaveFileDialog so the user can save the Image 
      // assigned to Button2. 
      SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 
      saveFileDialog1.Filter = "Text File|*.txt|Log File|*.log"; 
      saveFileDialog1.Title = "Save Log File"; 
      saveFileDialog1.ShowDialog(); 

      // If the file name is not an empty string open it for saving. 
      if (saveFileDialog1.FileName != "") 
      { 
       // Saves the Image via a FileStream created by the OpenFile method. 
       System.IO.FileStream fs = 
        (System.IO.FileStream)saveFileDialog1.OpenFile(); 
       // Saves the Image in the appropriate ImageFormat based upon the 
       // File type selected in the dialog box. 
       // NOTE that the FilterIndex property is one-based. 
       switch (saveFileDialog1.FilterIndex) 
       { 
        case 1: 

         try 
         { 
          this.logWindow.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText); 
         } 
         catch (Exception ex) 
         { 
          MessageBox.Show(ex.ToString()); 
         } 


         break; 
        case 2: 

         try 
         { 
          this.logWindow.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText); 
         } 
         catch (Exception ex) 
         { 
          MessageBox.Show(ex.ToString()); 
         } 

         break; 
       } 

       fs.Close(); 
       OnFileDialogClose(this, new EventArgs()); 
      } 
} 

回答

3

似乎同一個文件打開兩次。首先,您使用創建它:

System.IO.FileStream fs = 
        (System.IO.FileStream)saveFileDialog1.OpenFile(); 

然後,你將相同的文件名this.logWindow.SaveFile,這大概打開與給定名稱的文件,將數據保存到它。

我想第一個電話是不必要的。

+0

謝謝,是它 –

相關問題