我想問如何使用二進制格式化程序創建和寫入文本文件我寫了下面的代碼,但我有一個例外。 的例外是: 文件無法訪問,因爲它已被另一個進程使用。文件和二進制格式化器
和我的代碼創建兩個文件之一是擴展名爲「.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
}
**什麼是異常說** ?你讀過它嗎? – SLaks
文件無法被訪問,因爲它已被另一個進程使用,並且它創建兩個文件,一個文件的擴展名爲「.txt」,另一個沒有任何擴展名。 – Tolen
編號'FileStream'只創建您指定的文件。我猜你已經在你的代碼的其他地方創建了這個文件,並且沒有關閉它的句柄。在另一篇文章中,我已經向你發送了一個可以正常工作的代碼。 – Venson