0
public static List<Restaurant> LoadRestaurantList() 
{
    FileStream fs = new FileStream("Restaurant.txt", FileMode.OpenOrCreate); 
    BinaryFormatter bf = new BinaryFormatter(); 
    List<Restaurant> rest =(List<Restaurant>)bf.Deserialize(fs); 
    fs.Close(); 
    return rest; 
}

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".

This is the Serialization code:

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(); 
}

Can anyone please help in solving out this.

5
  • 1
    where is your serialization code? Commented May 6, 2014 at 15:55
  • What does bf.Deserialize(fs) give you before you cast it? Commented May 6, 2014 at 15:56
  • 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(); } Commented May 6, 2014 at 16:06
  • my serialization code Commented May 6, 2014 at 16:06
  • Please add the above code to your question, not as a comment. No one can read that. Commented May 6, 2014 at 16:11

1 Answer 1

1

Serialization and Deserialization are each others opposites. This means the type(s) used during serialization needs to be the same during deserialization.

In your code that is not the case. You serialize Restaurant types but when you deserialize you expect a List.

Adapt your serialization code as follows:

public static void SaveRestaurantList(List<Restaurant> restaurantList) 
{ 
   using(FileStream fs = new FileStream("Restaurant.txt", FileMode.Create, FileAccess.Write))
   {
       BinaryFormatter bf = new BinaryFormatter(); 
       bf.Serialize(fs, restaurantList); 
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

how does this code stores the content in the form of List, so that I can use it while deserializing, can me explain me code little more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.