سؤال

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.

هل كانت مفيدة؟

المحلول

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); 
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top