Tolen
Tolen

Reputation: 111

Insertion data into text file exception

I have written a code that crates a text file called contact and then try to store data and read data from it.

I have no problem in storing data but how can I store new data without override the oldest one?

and when I am finishing the insertion process an exception occurred : that my text file can not be accessed because it is being used by another process. what should I do ??

here is my code:

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

Upvotes: 1

Views: 71

Answers (1)

meda
meda

Reputation: 45500

Use FileMode.Append to append to existing file

Upvotes: 1

Related Questions