2011-09-14 111 views
1

所以我一直試圖用不同的方法修復這個bug,並且沒有任何東西可以工作。這是我簡化了我的代碼,所以我可以看到發生了什麼問題。用一種方法打開文件,然後在另一個文件中寫入

我打電話open()方法首先打開文件,將它讀出我的變量。然後我調用save()並寫回到同一個文件。

然而,我得到一個錯誤說

,因爲它正被另一個進程使用

是否有一個解決方案的進程無法訪問文件{$ FILE}?

private void save() 
{ 
    if (currentFile == null) 
    { 
     saveAs(); 
    } 
    else 
    { 
     if (File.OpenWrite(currentFile) != null) 
     { 
      byte[] buffer = null; 
      if (currentEncoding == encoding.utf8) 
      { 
       buffer = System.Text.Encoding.UTF8.GetBytes(mainTxtBx.Text); 
      } 
      else 
      { 
       buffer = System.Text.Encoding.ASCII.GetBytes(mainTxtBx.Text); 
      } 
      File.WriteAllBytes(currentFile, buffer); 
     } 
    } 
} 

private void open() 
{ 
    OpenFileDialog openFileDialog = new OpenFileDialog(); 
    openFileDialog.InitialDirectory = homePath; 
    openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
    openFileDialog.FilterIndex = 2; 
    openFileDialog.RestoreDirectory = true; 
    if (openFileDialog.ShowDialog() == DialogResult.OK) 
    { 
     currentFile = openFileDialog.FileName.ToString(); 
     openFileDialog.Dispose(); 
     if (File.Exists(currentFile)) 
     { 
      byte[] buffer = File.ReadAllBytes(currentFile); 
      if (currentEncoding == encoding.utf8) 
      { 
       mainTxtBx.Text = new string(System.Text.Encoding.UTF8.GetChars(buffer).ToArray()); 
      } 
      else 
      { 
       mainTxtBx.Text = new string(System.Text.Encoding.ASCII.GetChars(buffer).ToArray()); 
      } 
     } 
    } 
} 
+0

什麼時候關閉由File.OpenWrite創建的流? –

+0

@Paul從他的代碼,永遠不會因爲沒有引用該對象,所以它不可能關閉(除非GC開始調用終結器,我相信它被關閉,但不應該依賴 – Davy8

回答

4

由於您使用WriteAllBytes,你可以使用ReadAllBytesReadAllText代替OpenWrite

 

      byte[] buffer = File.ReadAllBytes(currentFile); 
      if (currentEncoding == encoding.utf8) 
      { 
       buffer = System.Text.Encoding.UTF8.GetBytes(mainTxtBx.Text); 
      } 
      else 
      { 
       buffer = System.Text.Encoding.ASCII.GetBytes(mainTxtBx.Text); 
      } 
      File.WriteAllBytes(currentFile, buffer); 
 
+0

哇,我擺脫了if語句,它的工作原理我猜這是因爲文件在塊後關閉了嗎? – ApocSama

+1

@Apocalypse no,這是因爲你的if語句打開文件但從不關閉它,所以'WriteAllBytes'當它已經打開時試圖再次打開它,'ReadAllBytes'和'WriteAllBytes'將會打開,讀/寫,並關閉所有這些單獨的方法調用,你自己調用'Open'意味着你需要自己關閉它 – Davy8

2

問題出在線if (File.OpenWrite("test.txt") != null)。 File.OpenWrite打開文件進行寫入並返回FileStream。你打開該文件,然後,而文件仍處於打開狀態,試圖寫入文件中的聲明File.WriteAllBytes(currentFile, buffer);

嘗試沿着這些路線的東西:

 var writer = File.OpenWrite("test.txt"); 
     using (writer) 
     { 
      byte[] buffer = null; 
      //... 
      writer.Write(buffer, 0, buffer.Length); 
     } 
1

你不需要if條件if (File.OpenWrite(currentFile) != null)

這將打開該文件,並再次你試圖打開相同的文件,並使用WriteAllBytes

1

有幾個問題,並與代碼中潛在的問題寫T0,但最直接的一個是WriteAllBytes不需要調用OpenWrite

當你調用OpenWrite你打開的文件與所返回該文件對象寫,你不允許其他任何試圖打開該文件,直到它再次關閉。因爲你永遠不會打電話給Dispose,它會一直處於鎖定狀態,直到你的程序退出。

與代碼無關的問題是,如果結果爲OK,那麼只處理對話框時,應該始終處理該對話框。您應該查看using聲明來處理資源處置。即使發生異常,也需要調用Dispose,因此您需要將使用一次性對象的代碼打包到try..finally中,或使用using這樣做。

相關問題