문제

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