我编写了一个代码来创建一个名为contact的文本文件,然后尝试存储数据并从中读取数据。
我在存储数据方面没有问题,但是如何在不覆盖最旧数据的情况下存储新数据?
当我完成插入过程时发生异常:我的文本文件无法访问,因为它正在被另一个进程使用。我应该怎么办 ??
这是我的代码:
using System;
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 ");
}
public void viewContact
{
FileStream file = new FileStream("contact.txt", FileMode.Open, FileAccess.Read);
BinaryFormatter bin = new BinaryFormatter();
List<string> contact_list = new List<string>();
//while (file != null)
using (StreamReader read = new StreamReader("contact.txt"))
{
string temp = read.ReadToEnd();
contact_list.Add(temp);
} file.Close();
for (int i = 0; i < contact_list.Count; i++)
{
Console.WriteLine(contact_list[i]);
}
}
}//end of class