Link to home
Start Free TrialLog in
Avatar of Cyber-Drugs
Cyber-DrugsFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Modifying Serialization

Hi guys,

I managed to get a program which can do Serialization for me:

https://www.experts-exchange.com/questions/21850587/Reading-and-Writing-a-custom-Binary-File.html

But now I need to either modify it a bit, so that I can store endless records, rather than static amounts of data, or if someone could show me a better way of storing endless records in a binary file, that would be great.

Anyone able to help me out please?
Avatar of 2266180
2266180
Flag of United States of America image

well .. something like this would do?

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

namespace ReadingWritingCustomBinaryFile
{
    [Serializable]
    class Article : ISerializable
    {
        // any Fields
        private string author = String.Empty;
        private string text = String.Empty;
        private string title = String.Empty;

#region these 2 constructors is needed for the deserialization used by the formater
        public Article(SerializationInfo info, StreamingContext context)
        {
            Title = info.GetValue("Title", typeof(string)).ToString();
            Author = info.GetValue("Author", typeof(string)).ToString();
            Text = info.GetValue("Text", typeof(string)).ToString();
        }

        public Article()
        {
            //Empty Constructor
        }
#endregion


        public string Author
        {
            get { return author; }
            set { author = value; }
        }

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }


        #region this method is needed for Serializationused by the formater
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Title", Title);
            info.AddValue("Text", Text);
            info.AddValue("Author", Author);
        }
        #endregion

        // to serialize this instance
        public void Serialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite);
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
                s.Close();
            }
        }

        public void Serialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
            }
        }

        // to deserialize from a file and return object
        public static Article Deserialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Open, FileAccess.Read);
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
                s.Close();
            }
        }

        public static Article Deserialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
            }
        }
    }
}

and using it would be something like:

create a list of articles
Article[] articles;
then
FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);
for (i=0; i<articles.lentgh; i++)
  articles[i].Serialize(f);
and loading:
for (i=0; i<articles.lentgh; i++)
  articles[i] = Article.Deserialize(f);


not tested but should work right out of the box (don't have a VS IDE handy)
Avatar of Cyber-Drugs

ASKER

About to test it, but before I do, is this correct?

FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);

Or did you mean to put...

FileStream f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);


?
the 2 lines look the same to me ...
Filestram

Filestream
oh. sorry :D you are right it was a typo. may bad.
OK, I get one error when I compile...


Use of unassigned local variable 'articles'
well  of ocurse, I just outlined the use of the variables. that was not a full implementation but a sketch.

here is a more complete example of use (still in a sketch form):

create a list of articles

save articles (you must create some. I will only create one)
Article[] articles=new articles[1];
articles[0] = new Article();
articles[0].Author = "first auth";
articles[0].Text = "some text";
articles[0].Title = "some title";
FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite);
for (i=0; i<articles.lentgh; i++)
  articles[i].Serialize(f);

and loading:
using System.Collenctions;
ArrayList articles = new ArrayList;
FileStram f = new FileStream(Filename, FileMode.Open, FileAccess.Read);
while (f.Position<f.Length)//some EOF like check
  articles.add(Article.Deserialize(f));

to access an element from the arraylist, you just do a cast like:
Article article = (Article)articles.Itme[0];

you should be able to compile this and run it (after integrating it in your test app). the code might conatin typos. Sorry if there are any.
Still getting one error:

Error      1      The type or namespace name 'articles' could not be found (are you missing a using directive or an assembly reference?)      C:\Documents and Settings\Justin Nel\My Documents\Visual Studio 2005\Projects\CustomFile\CustomFile\Form1.cs      57      38      CustomFile


Sorry for the slow reply, had a busy day in the office today.
I am sure you forgot to copy something as in my examples (both of them) articles is defined. in the first one as an array of Article and in the second as an ArrayList. check your code. alternativly, post it here so we can see it
I checked, but I couldn't see the problem, so here is what I have in the code so far....


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

namespace ReadingWritingCustomBinaryFile
{
    [Serializable]
    class Article : ISerializable
    {
        // any Fields
        private string author = String.Empty;
        private string text = String.Empty;
        private string title = String.Empty;

        #region these 2 constructors is needed for the deserialization used by the formater
        public Article(SerializationInfo info, StreamingContext context)
        {
            Title = info.GetValue("Title", typeof(string)).ToString();
            Author = info.GetValue("Author", typeof(string)).ToString();
            Text = info.GetValue("Text", typeof(string)).ToString();
        }

        public Article()
        {
            //Empty Constructor
        }
        #endregion


        public string Author
        {
            get { return author; }
            set { author = value; }
        }

        public string Text
        {
            get { return text; }
            set { text = value; }
        }

        public string Title
        {
            get { return title; }
            set { title = value; }
        }


        #region this method is needed for Serializationused by the formater
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Title", Title);
            info.AddValue("Text", Text);
            info.AddValue("Author", Author);
        }
        #endregion

        // to serialize this instance
        public void Serialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite);
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
                s.Close();
            }
        }

        public void Serialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(s, this);
            }
            finally
            {
            }
        }

        // to deserialize from a file and return object
        public static Article Deserialize(string Filename)
        {
            Stream s = null;
            try
            {
                s = File.Open(Filename, FileMode.Open, FileAccess.Read);
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
                s.Close();
            }
        }

        public static Article Deserialize(Stream s)
        {
            try
            {
                BinaryFormatter b = new BinaryFormatter();
                return (Article)b.Deserialize(s);
            }
            finally
            {
            }
        }
    }
}









and on the form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ReadingWritingCustomBinaryFile;
using System.IO;
using System.Collections;

namespace CustomFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Article CurrentArticle = new Article();

        private void btnSerialize_Click(object sender, EventArgs e)
        {
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SaveArticle();
                CurrentArticle.Serialize(this.saveFileDialog1.FileName);
            }
        }

        private void btnDeserialize_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                CurrentArticle = Article.Deserialize(this.openFileDialog1.FileName);
                LoadArticle();
            }
        }

        private void LoadArticle()
        {
            txtAuthor.Text = CurrentArticle.Author;
            txtText.Text = CurrentArticle.Text;
            txtTitle.Text = CurrentArticle.Title;
        }

        private void SaveArticle()
        {
            CurrentArticle.Author = txtAuthor.Text;
            CurrentArticle.Text = txtText.Text;
            CurrentArticle.Title = txtTitle.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int i;
            Article[] articles = new articles[1];
            articles[0] = new Article();
            articles[0].Author = "first author";
            articles[0].Text = "some text";
            articles[0].Title = "some title";
            FileStream f = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite);
            for (i=0; i<articles.Length; i++)
            {
                articles[i].Serialize(f);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ArrayList articles = new ArrayList;
            FileStream f = new FileStream(this.openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
            while (f.Position<f.Length)
            {
                articles.Add(Article.Deserialize(f));
            }
        }
    }
}
ASKER CERTIFIED SOLUTION
Avatar of 2266180
2266180
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works absolutely beautifully!!!

Thank you VERY much!