0
public static void SaveRestaurantList(List<Restaurant> restaurantList)
    {           
        FileStream fs = new FileStream("Restaurant.txt", FileMode.Create, FileAccess.Write);
        BinaryFormatter bf = new BinaryFormatter();

        for (int i = 0; i < restaurantList.Count; i++)
        {
            Restaurant r = new Restaurant();
            r = (Restaurant)restaurantList[i];
            bf.Serialize(fs, r);
            fs.Flush();               
        }
        fs.Close();
        Console.WriteLine("\n\n\t\t File Get Serialized.., \n\t\t Close the Promt and Check in Application Debug Folder..!!");
     }

I have Serailze the generic list which I have, into "Restaurant.txt" file.

now I want to Deserialize the same and return it into a Generic List, I have tried but its not working and it is giving error "Invalid Cast Expression".

Can anyone please help in solving out this.

6
  • .txt is not binary. Commented May 4, 2014 at 3:40
  • What is the exact error, and where does it happen? Commented May 4, 2014 at 3:40
  • I mean to say that, I need to save the List of Restaurant (but not the entire Dictionary) into Restaurants.txt file under application folder using binary serialization. & I did that now I want deserialize it and show the result on console by returning it into List Commented May 4, 2014 at 3:46
  • FileStream fs = new FileStream("Restaurant.txt", FileMode.OpenOrCreate); BinaryFormatter bf = new BinaryFormatter(); List<Restaurant> restaurant = new List<Restaurant>(); restaurant = (List<Restaurant>)bf.Deserialize(fs); fs.Close(); return restaurant; Commented May 4, 2014 at 3:47
  • @AnjaliD.Kapadni show us your deserialization code.. Commented May 4, 2014 at 3:47

2 Answers 2

1

You should serialize the complete list itself.

using (Stream stream = File.Open("data.bin", FileMode.Create))
{
    BinaryFormatter bin = new BinaryFormatter();
    bin.Serialize(stream, restaurantList);
}

You can later deserialize the complete list like this

using (Stream stream = File.Open("data.bin", FileMode.Open))
{
    BinaryFormatter bin = new BinaryFormatter();
    var restaurantList=(List<Restaurant>)bin.Deserialize(stream);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Its not working and giving the error as Invlid Argument exception... :(
restaurantList = (List<Restaurant>)bf.Deserialize(fs); at this line my code is giving error as InvalidCastException was unhandled
0

Kapadni,

I am storing my list/BindingList of object in .xml file and may be below functions/code will help you to serialize and de-serialize object and store/retrieve from .xml file

BindingList<IntradayData> objIntradayDataList;
        SerializeObject(objIntradayDataList, filepath);
        objIntradayDataList = DeSerializeObject<BindingList<IntradayData>>(filepath);

 public void SerializeObject<T>(T serializableObject, string fileName)
    {
        if (serializableObject == null) { return; }

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, serializableObject);
                stream.Position = 0;
                xmlDocument.Load(stream);
                xmlDocument.Save(fileName);
                stream.Close();
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            log.Error("SerializeObject ", ex);

        }
    }

    public T DeSerializeObject<T>(string fileName)
    {
        if (string.IsNullOrEmpty(fileName)) { return default(T); }

        T objectOut = default(T);

        try
        {
            string attributeXml = string.Empty;

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(fileName);
            string xmlString = xmlDocument.OuterXml;

            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(T);

                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    objectOut = (T)serializer.Deserialize(reader);
                    reader.Close();
                }

                read.Close();
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            log.Error("DeSerializeObject ", ex);

        }

        return objectOut;
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.