Click here to Skip to main content
16,011,428 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The data is loaded from the database using a dataset which saves the data to the arraylist/array

What code can I use to achieve this?
Posted

1 solution

Try this code to store your object in xml format, you can dump and read that to a simple file.txt

using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace  Put.Here.Your.Proyects.Namespace
{
    public class Serializer
    {
        public static string Serialize(Type typeOfObj, object obj)
        {
            Stream memStm = new MemoryStream();
            StreamWriter tw = new StreamWriter(memStm);

            XmlSerializer serializadorXML = new XmlSerializer(typeOfObj);
            serializadorXML.Serialize(tw, obj);
            memStm.Position = 0;

            StreamReader stmRdr = new StreamReader(memStm);

            string text = stmRdr.ReadToEnd();
            tw.Close();
            return text.Trim();
        }

        public static object Deserialize(Type typeOfObj, string text)
        {
            object obj = null;
            
            ////Optional code
            //XmlReaderSettings settings = new XmlReaderSettings();
            //settings.ConformanceLevel = ConformanceLevel.Fragment;
            //settings.IgnoreWhitespace = true;
            //settings.IgnoreComments = true;
            //settings.IgnoreProcessingInstructions = true;

            byte[] byteArray = Encoding.UTF8.GetBytes(text);
            MemoryStream stream = new MemoryStream(byteArray);

            XmlReader xmlReader = XmlReader.Create(stream);//, settings);
            XmlSerializer serializadorXML = new XmlSerializer(typeOfObj);

            if (serializadorXML.CanDeserialize(xmlReader))
            {
                obj = serializadorXML.Deserialize(xmlReader);
            }

            return obj;
        }
    }
}


to serialize use typeof like example:
string xmlText = Serialize(typeOf miObjectClassName, myObject);


to deserealize cast object:
miObjectClassName myObject = (miObjectClassName)Deserialize(typeOf miObjectClassName, xmlText);


you can remove static label to fuction but I recomend not because you can use fuction like utility without need to create object:
string x = Put.Here.Your.Proyects.Namespace.Serialize(typeOf miObjectClassName, myObject);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900