我使用BinaryFormatter序列化和反序列化自定義文件類型。我有一個獨立的應用程序和一個Web應用程序,它們都可以讀取和寫入相同的文件。獨立應用程序工作正常,但是當我用我的Web應用程序讀取文件時,會引發異常。問題是我看不清究竟是怎麼回事,我該如何調試或修復這個錯誤?binaryFormatter.Deserialize(stream):調試和修復錯誤
BinaryFormatter b = new BinaryFormatter();
b.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
b.Binder = new WebBinder();
object o = b.Deserialize(s); //Throws exception :
對象類型的 'System.String' 不能被轉換爲類型 'System.Decimal'。
public class WebBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type tyType = null;
string sShortAssemblyName = assemblyName.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ayAssembly in ayAssemblies)
{
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
{
tyType = ayAssembly.GetType(typeName);
break;
}
}
return tyType;
}
}
相同文件中的獨立的應用程序進行反序列化細??
異常告訴你,你正試圖反序列化一個Decimal,但是序列化的是一個String。 –
您是否嚴格與BinaryFormatter綁定?一個序列化程序*不依賴於類型*可能是一個好主意 –
@MarcGravell:我很好奇,你的意思是一個*類型依賴序列化程序*,它在某種意義上是/ d序列化程序依賴於* MEM。大小和佈局*的類型或其他? –