2012-10-26 21 views
2

在探索創建文本文件我碰到這種行爲迷迷糊糊的選項我無法解釋理解爲什麼C#文件創建選項碰撞

兩個按鈕將創建一個文件

但是當我建立一個檔案,Button1的按鈕2生成一個錯誤。

這隻發生在文件實際創建時。

後一個文件被創建按鈕1和兩個預期

一個簡單的GUI程序的示例代碼2個按鈕和包圍的multilne文本框操作

string logFile; 

    public Form1() 
    { 
     InitializeComponent(); 

     logFile = "test.txt"; 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

     if (!System.IO.File.Exists(logFile)) 
     { 
      System.IO.File.Create(logFile); 
      textBox1.AppendText("File Created\r\n"); 
     } 
     else 
     { 
      textBox1.AppendText("File Already Exists\r\n"); 
     } 

     System.IO.File.AppendText("aaa"); 

    } 

    private void button2_Click(object sender, EventArgs e) 
    { 

     // 7 overloads for creation of the Stream Writer 

     bool appendtofile = true; 

     System.IO.StreamWriter sw; 

     try 
     { 
      sw = new System.IO.StreamWriter(logFile, appendtofile, System.Text.Encoding.ASCII); 
      sw.WriteLine("test"); 
      textBox1.AppendText("Added To File Created if Needed\r\n"); 
      sw.Close(); 

     } 
     catch (Exception ex) 
     { 
      textBox1.AppendText("Failed to Create or Add\r\n"); 

      // note this happens if button 1 is pushed creating the file 
      // before button 2 is pushed 
      // eventually this appears to resolve itself 

      textBox1.AppendText("\r\n"); 
      textBox1.AppendText(ex.ToString()); 
      textBox1.AppendText("\r\n"); 
      textBox1.AppendText(ex.Message); 
     } 



    } 
+3

什麼是錯誤信息?我的猜測是,當您嘗試第二次調用時,該文件仍然會在第一次調用時打開。 –

+2

異常消息? – mservidio

回答

4

你可能會得到,因爲文件的錯誤前一個進程正在使用資源。在使用資源(如文件)(並使用StreamWriter對象,它是IDisposable)時,建議使用「Using」指令。這將在代碼執行完成後關閉資源。

using (StreamWriter sw = File.CreateText(path)) 
      { 
       sw.WriteLine("Hello"); 
       sw.WriteLine("And"); 
       sw.WriteLine("Welcome"); 
      } 

一旦你寫的第三行,文件將自動關閉,並配置資源。