C# how to save an object into a fine or database?

Started by
3 comments, last by flyinger 15 years, 11 months ago
how do i save an object into a database or a file with the simplest coding. NOTE: there is class inheritance eg: parent class and child class. i need to do this for my project, so pls help me :(
Advertisement
Hi,

If you want to save the object as a file I would suggest using a BinaryFormatter and writing the object to an .xml file on the disk. If you want to save the object into a database then you could use some of the ADO.Net stuff - I used it a while ago and it was OK, I suppose there's probably something better out there now though, database's aren't really my thing.

Anyway, have a look at Serializing objects in C#, the BinaryFormatter and saving files to disk in C#. Googling those should get you all the answers you want - if you get stuck with something post some questions about it on here.

Also, the MSDN (both online and the library that you can install with VS) has really good articles on this.

Cheers,

James
quote:"using a BinaryFormatter and writing the object to an .xml file on the disk."

that means i need to know binary formatter to write the object to an .xml file?

i already know about saving an array to xml file, but i do not know about using BinaryFormatter.

can you show a simple coding of it? so i try and learn it. i'll try to find out by searching in google as well. i need to see a simple code cause i afraid i may not be able to find it. thanks for your suggestions for binary formatter. ^^
Serriously, the MSDN is your friend, use it! Here's some info from there on the BinaryFormatter class (Clicky).

Here is an example of my own:


A Serializable Class
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Serialization;namespace SerializableExample{    [Serializable]    public class SerializableClass : ISerializable    {        #region Properties        public string SomeString {set;get;}        public int SomeInt {set;get;}        public DateTime SomeDate {set;get;}        #endregion        #region Methods        #region Constructors        /// <summary>        /// Default constructor.        /// </summary>        public SerializableClass()        {        }        /// <summary>        /// Constructor used when deserializing the data into the object.        /// </summary>        /// <param name="info"></param>        /// <param name="context"></param>        public SerializableClass(SerializationInfo info, StreamingContext context)        {            this.SomeString = info.GetString("SomeString");            this.SomeInt = info.GetInt32("SomeInt");            this.SomeDate = (DateTime)info.GetValue("SomeDate", typeof(DateTime));        }        #endregion                #region ISerializable Members        /// <summary>        /// This method is used to serialize the data.        /// </summary>        /// <param name="info"></param>        /// <param name="context"></param>        public void GetObjectData(SerializationInfo info, StreamingContext context)        {            info.AddValue("SomeString", this.SomeString);            info.AddValue("SomeInt", this.SomeInt);            info.AddValue("SomeDate", this.SomeDate);        }        #endregion        #endregion    }}



A Method That Uses BinaryFormatter To Write It To Disk
        // Serialize        private void SerializeMethod(object sender, EventArgs e)        {            // Create object            SerializableClass s = new SerializableClass();            s.SomeString = "Something";            s.SomeInt = 675;            s.SomeDate = DateTime.Now;            // Serialize it            // Create a filestream and name the xml file the data will go into            Stream fileStream = File.Open(@"C:\myBinaryXMLFile.xml", FileMode.Create, FileAccess.ReadWrite, FileShare.None);            // Create binary formatter to serialise the data            BinaryFormatter binaryFormatter = new BinaryFormatter();            // Serialise the data            binaryFormatter.Serialize(fileStream, s);            // Flush and close the filestream            fileStream.Flush();            fileStream.Close();        }


A Method That Reads It From Disk
        // Deserialize        private void DeserializeMethod(object sender, EventArgs e)        {            // Create an object to return            SerializableClass s = null;            // Create a filestream and a binary formatter            Stream fileStream = null;            BinaryFormatter binaryFormatter = new BinaryFormatter();            // Open the file exclusively            fileStream = File.Open(@"C:\myBinaryXMLFile.xml", FileMode.Open, FileAccess.Read, FileShare.None);            // Deserialize into the object            s = (SerializableClass)binaryFormatter.Deserialize(fileStream);            // Close the streams            if (fileStream != null)                fileStream.Close();        }


At the moment those two methods wont actually do anything with the data but if you do use the code, run it in debug mode and stick break points on the lines where it reads the data in to an object. Also I have no idea if that code will work, I just did it off the top of my head - Oh, and you'll need to add some using statements (System.IO and System.Runtime.Serialization.Formatters.Binary I think).

Seriously though, go and search for the specific things I mentioned in my previous post - There are hundreds of articles on this, none better than the examples given by Microsoft on the MSDN - READ THEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Cheers,

James

EDIT: Edited method names to make more sense.

[Edited by - JamesLewis on May 14, 2008 9:12:18 AM]
wow, thanks for your effort for posting here, i'll try to understand whats going on in the coding.^^

This topic is closed to new replies.

Advertisement