Jump to content

C#: Serialization/Deserialization of List<T>

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
scottk

scottk

    Learning Programmer

  • Members
  • PipPipPip
  • 35 posts
Here is an example of serialization and deserialization of business objects. This example writes the xml out to a file:

  public class InventoryItem

  {

    public string ItemName { get; set; }

    public string ItemNumber { get; set; }

    public decimal Price { get; set; }

    public int QtyOnHand { get; set; }

    public InventoryItem()

    {

    }

    public static void Save(List<InventoryItem> List, string FileName)

    {

      //create a backup

      string backupName = Path.ChangeExtension(FileName, ".old");

      if (File.Exists(FileName))

      {

        if (File.Exists(backupName))

          File.Delete(backupName);

        File.Move(FileName, backupName);

      }


      using (FileStream fs = new FileStream(FileName, FileMode.Create))

      {

        XmlSerializer ser = new XmlSerializer(typeof(List<InventoryItem>));

        ser.Serialize(fs, List);

        fs.Flush();

        fs.Close();

      }

    }

    public static List<InventoryItem> Load(string FileName)

    {

      if (!File.Exists(FileName))

        throw new FileNotFoundException("The inventory file could not be found", FileName);


      List<InventoryItem> result;


      using (FileStream fs = new FileStream(FileName, FileMode.Open))

      {

        XmlSerializer ser = new XmlSerializer(typeof(List<InventoryItem>));

        result = (List<InventoryItem>)ser.Deserialize(fs);

      }

      return result;

    }

  }



#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Hey Scottk, I moved this to the code section since it isn't a tutorial. Cool bit of code, thanks for sharing! :)

Edited by Jordan, 20 July 2009 - 03:43 PM.


#3
scottk

scottk

    Learning Programmer

  • Members
  • PipPipPip
  • 35 posts
Ah, I did miss the code snippet forum! Thanks for cleaning up behind me -- I'll make sure to get future posts in the right forum.

Thanks
Scott Knake
Custom Software
Apex Software, Inc.

#4
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
What are business objects? Is that a special type of object or just a name you made up for this object?

#5
scottk

scottk

    Learning Programmer

  • Members
  • PipPipPip
  • 35 posts
Neither, it is a concept: Business object (computer science) - Wikipedia, the free encyclopedia

[edit]Well I guess that would be considered a special type of object[/edit]
Scott Knake
Custom Software
Apex Software, Inc.

#6
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Interesting. +rep for teaching me something. :)