2013-08-05 80 views
-1

我想問如何使用二進制格式化程序創建和寫入文本文件我寫了下面的代碼,但我有一個例外。 的例外是: 文件無法訪問,因爲它已被另一個進程使用。文件和二進制格式化器

和我的代碼創建兩個文件之一是擴展名爲「.txt」,另一個沒有任何擴展名。

我該怎麼辦? 是否有另一種創建文本文件的方式?

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.Runtime.Serialization; 


namespace ConsoleApplication9 
{ 
    [Serializable] 
    class contact 
    { 



     string name; 
     string address; 
     string phonenumber; 
     string emailaddress; 
     public override string ToString() 
     { 
      return name + " " + address + " " + phonenumber + " " + emailaddress; 
     } 

     public void AddContent(string cname, string caddress, string cphone, string cemail) 
     { 
      name = cname; 
      address = caddress; 
      phonenumber = cphone; 
      emailaddress = cemail; 

      FileStream file = new FileStream("contact.txt", FileMode.OpenOrCreate, FileAccess.Write); 

      BinaryFormatter bin = new BinaryFormatter(); 
      contact person = new contact(); 
      person.name = cname; 
      person.address = caddress; 
      person.phonenumber = cphone; 
      person.emailaddress = cemail; 
      bin.Serialize(file, person); 
      file.Close(); 

      Console.WriteLine(" added sucefully"); 


     }//end of fun add 

}

+6

**什麼是異常說** ?你讀過它嗎? – SLaks

+0

文件無法被訪問,因爲它已被另一個進程使用,並且它創建兩個文件,一個文件的擴展名爲「.txt」,另一個沒有任何擴展名。 – Tolen

+0

編號'FileStream'只創建您指定的文件。我猜你已經在你的代碼的其他地方創建了這個文件,並且沒有關閉它的句柄。在另一篇文章中,我已經向你發送了一個可以正常工作的代碼。 – Venson

回答

2

您的異常與BinaryFormatter無關,但與您不正確處理FileStream的事實相反。總是包流在一個使用塊:

using(FileStream file = new FileStream("contact.txt", FileMode.OpenOrCreate, FileAccess.Write)) 
{ 
    //code here 
} 

這保證了流下方閉合且非託管資源被釋放。特別是在你的情況下,似乎操作系統仍然鎖定你正在嘗試創建的文件,並且第二次運行你的代碼會拋出關於你的文件的異常being used by another process

+0

非常感謝這是缺少的。 – Tolen

0
file can not been access because it is has been used by another process. 

有沒有可能是你可能在advertantly打開這個文件和它在文本窗口仍處於打開狀態?