2013-08-22 42 views
2

我一直在努力克隆記事本,但遇到了問題。 當我嘗試在文本框中的文本寫入其中我創建了一個文件,我得到異常:寫入文件時出現「無法訪問文件」

該進程無法訪問文件「C:\用戶\ opeyemi \文檔\ b.txt」 因爲它正在被另一個進程使用。

下面是我寫的代碼。我非常感謝任何有關我下一步應該做什麼的建議。

private void Button_Click_1(object sender, RoutedEventArgs e) 
{ 
    SaveFileDialog TextFile = new SaveFileDialog(); 
    TextFile.ShowDialog(); 
    // this is the path of the file i wish to save 
    string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),TextFile.FileName+".txt"); 
    if (!System.IO.File.Exists(path)) 
    { 
     System.IO.File.Create(path); 
     // i am trying to write the content of my textbox to the file i created 
     System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path); 
     textWriter.Write(textEditor.Text); 
     textWriter.Close(); 
    } 
} 
+2

_「我真的很感激的是我應該做的下一任何意見」 _ - 無需在網上搜索時收到錯誤不開放的問題。在這裏每兩天詢問一個關於'File.Create()'鎖定文件的問題。 – CodeCaster

+0

[File正在被其他進程使用File.Create()]後可能的重複(http://stackoverflow.com/questions/2781357/file-being-used-by-another-process-after-using-file-創建) – CodeCaster

回答

5

必須 「保護」 你StremWriter使用(閱讀)在using,如:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path)) 
{ 
    textWriter.Write(textEditor.Text); 
} 

沒有必要.Close()

你不需要System.IO.File.Create(path);,因爲StreamWriter會爲你創建的文件(和Create()返回你保持開放的代碼中的FileStream

技術上你可以:

File.WriteAllText(path, textEditor.Text); 

這是所有功能於一身的和做的一切(打開,寫,關閉)

或者,如果你真的想使用的StreamWriter和File.Create:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(System.IO.File.Create(path))) 
{ 
    textWriter.Write(textEditor.Text); 
} 

(有一個StreamWriter構造接受FileStream

+0

感謝您的意見。它現在正在工作,但我仍然想知道爲什麼當我使用.close它沒有。當我嘗試使用聲明時,它也不起作用。 – opeyemi

+0

@opeyemi這:'System.IO.File.Create(path);'創建一個文件並保持它打開。接下來是:創建一個文件並保持打開狀態的新System.IO.StreamWriter(路徑)。你看到問題了嗎?兩條指令試圖打開文件。 'File.Create'不是「創建零字節文件並關閉它」。這是「創建一個文件並保持打開狀態」。它不是'void Create(path)',它是'FileStream Create(path)'。技術上你可以有'File.Create(path).Close();'但它沒用。 – xanatos

+0

感謝您的幫助。 – opeyemi