trying to serialize and deserialize entity object in c# - c#

I am using two methods below to serialize/deserialize entity framework object (ver. 4.0).
I tried several ways to accomplish this, and had no luck. Serialization works fine. I get nice xml formatted string, but when I try to deserialize I get error in XML. How is that possible?
Thanks.
public static string SerializeObject(Object obj)
{
XmlSerializer ser = new XmlSerializer(obj.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, obj);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
string xml = doc.InnerXml;
return xml;
}
public static object DeSerializeAnObject(string xml, Type objType)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(objType);
object obj = ser.Deserialize(reader);
return obj;
}

I use generic methods to serialize and deserialize:
/// <summary>
/// Serializes an object to Xml as a string.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="ToSerialize">Object of type T to be serialized.</param>
/// <returns>Xml string of serialized type T object.</returns>
public static string SerializeToXmlString<T>(T ToSerialize)
{
string xmlstream = String.Empty;
using (MemoryStream memstream = new MemoryStream())
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
XmlTextWriter xmlWriter = new XmlTextWriter(memstream, Encoding.UTF8);
xmlSerializer.Serialize(xmlWriter, ToSerialize);
xmlstream = UTF8ByteArrayToString(((MemoryStream)xmlWriter.BaseStream).ToArray());
}
return xmlstream;
}
/// <summary>
/// Deserializes Xml string of type T.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="XmlString">Input Xml string from which to read.</param>
/// <returns>Returns rehydrated object of type T.</returns>
public static T DeserializeXmlString<T>(string XmlString)
{
T tempObject = default(T);
using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(XmlString)))
{
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
tempObject = (T)xs.Deserialize(memoryStream);
}
return tempObject;
}
// Convert Array to String
public static String UTF8ByteArrayToString(Byte[] ArrBytes)
{ return new UTF8Encoding().GetString(ArrBytes); }
// Convert String to Array
public static Byte[] StringToUTF8ByteArray(String XmlString)
{ return new UTF8Encoding().GetBytes(XmlString); }

i THINK the issue is with this line:
string xml = doc.InnerXml;
you want ALL the xml, not just the xml inside the root node.

Just return sb.ToString(), loading into the XmlDocument is not doing anything.

Some redundancies and usings was excluded. Refactored and cleaned up:
namespace MyProject
{
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public static class Serializer
{
#region Public Methods and Operators
/// <summary>
/// Deserializes Xml string of type T.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="XmlString">Input Xml string from which to read.</param>
/// <returns>Returns rehydrated object of type T.</returns>
public static T DeserializeXmlString<T>(string xmlString)
{
T tempObject;
using (var memoryStream = new MemoryStream(StringToUTF8ByteArray(xmlString)))
{
var xs = new XmlSerializer(typeof(T));
tempObject = (T)xs.Deserialize(memoryStream);
}
return tempObject;
}
/// <summary>
/// Serializes an object to Xml as a string.
/// </summary>
/// <typeparam name="T">Datatype T.</typeparam>
/// <param name="toSerialize">Object of type T to be serialized.</param>
/// <returns>Xml string of serialized type T object.</returns>
public static string SerializeToXmlString<T>(T toSerialize)
{
string xmlstream;
using (var memstream = new MemoryStream())
{
var xmlSerializer = new XmlSerializer(typeof(T));
var xmlWriter = new XmlTextWriter(memstream, Encoding.UTF8);
xmlSerializer.Serialize(xmlWriter, toSerialize);
xmlstream = UTF8ByteArrayToString(((MemoryStream)xmlWriter.BaseStream).ToArray());
}
return xmlstream;
}
#endregion
#region Methods
private static byte[] StringToUTF8ByteArray(string xmlString)
{
return new UTF8Encoding().GetBytes(xmlString);
}
private static string UTF8ByteArrayToString(byte[] arrBytes)
{
return new UTF8Encoding().GetString(arrBytes);
}
#endregion
}
}

Related

Serialize/deserialize without external library in c#

How do i serialize/de serialize JSON data in c# without using any library or nugget package
i tried this
it allways shows me error!
{
/// <summary>
/// Deserialize an from json string
/// </summary>
public static T Deserialize<T>(string body)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(body);
writer.Flush();
stream.Position = 0;
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
}
}
/// <summary>
/// Serialize an object to json
/// </summary>
public static string Serialize<T>(T item)
{
using (MemoryStream ms = new MemoryStream())
{
new DataContractJsonSerializer(typeof(T)).WriteObject(ms, item);
return Encoding.Default.GetString(ms.ToArray());
}
}
}```
System.Text.Json as a library from Microsoft and Newtonsoft.Json, an external serializer friend.
Dotnet has a library for your request Source page
string jsonString = JsonSerializer.Serialize(weatherForecast);
var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString);

C# Loading in Data with XML File [duplicate]

I'm basically looking for someone to point me in the right direction on this. I read through some of the Microsoft documentation, but that wasn't very helpful. This is my first attempt at working with XML.
I'm writing an application that needs to store a list of known users and a list of aliases created by each of those users. I've figured out how to have my lists serialized and stored to XML files when the application closes and have it retrieve those when the application opens again, but I don't want to keep the list of users and aliases in memory.
In order for this to work, I need to have the ability to search, edit, and append to the XML file during run time.
The XML structure I envision is something like:
<UserRecord>
<User>Username-1</User>
<AliasRecord>
<Alias>Alias-1</Alias>
<Number>6135551234</Number>
</AliasRecord>
<AliasRecord>
<Alias>Alias-2</Alias>
<Number>6131238888</Number>
</AliasRecord>
</UserRecord>
Each user would only have one username but could have multiple aliases. I need to have the ability to add users, add aliases to a new or existing user, and change existing aliases. Usernames would never change, but an entire User record could be deleted.
So far, the only XML I've done in C# uses serialization but I don't think that approach will work for the above.
private void WriteXML()
{
try
{
System.Xml.Serialization.XmlSerializer XMLwriter = new System.Xml.Serialization.XmlSerializer(typeof(MessageRecord));
System.IO.StreamWriter XMLfile = new System.IO.StreamWriter("Saved MessageRecords.xml");
foreach (MessageRecord mr in OutgoingMessages)
{
XMLwriter.Serialize(XMLfile, mr);
}
XMLfile.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Create two classes to represent UserRecord and AliasRecord.
public class UserRecord
{
public string User { get; set; }
public List<AliasRecord> AliasRecords { get; set; }
}
public class AliasRecord
{
public string Alias { get; set; }
public string Number { get; set; }
}
Populate them like this:
var userRecord = new UserRecord
{
User = "UserName1",
AliasRecord = new List<AliasRecord> {
new AliasRecord { Alias = "Alias1", Number = "12345678" },
new AliasRecord { Alias = "Alias2", Number = "23456789" }
}
};
And use this code to serialize/deserialize it:
public static class XmlHelper
{
public static bool NewLineOnAttributes { get; set; }
/// <summary>
/// Serializes an object to an XML string, using the specified namespaces.
/// </summary>
public static string ToXml(object obj, XmlSerializerNamespaces ns)
{
Type T = obj.GetType();
var xs = new XmlSerializer(T);
var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, ws))
{
xs.Serialize(writer, obj, ns);
}
return sb.ToString();
}
/// <summary>
/// Serializes an object to an XML string.
/// </summary>
public static string ToXml(object obj)
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
return ToXml(obj, ns);
}
/// <summary>
/// Deserializes an object from an XML string.
/// </summary>
public static T FromXml<T>(string xml)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(xml))
{
return (T)xs.Deserialize(sr);
}
}
/// <summary>
/// Deserializes an object from an XML string, using the specified type name.
/// </summary>
public static object FromXml(string xml, string typeName)
{
Type T = Type.GetType(typeName);
XmlSerializer xs = new XmlSerializer(T);
using (StringReader sr = new StringReader(xml))
{
return xs.Deserialize(sr);
}
}
/// <summary>
/// Serializes an object to an XML file. (Fixed code)
/// </summary>
public static void ToXmlFile(object obj, string filePath)
{
var xs = new XmlSerializer(obj.GetType());
var ns = new XmlSerializerNamespaces();
var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };
ns.Add("", "");
using (XmlWriter writer = XmlWriter.Create(filePath, ws))
{
xs.Serialize(writer, obj, ns);
}
}
/// <summary>
/// Deserializes an object from an XML file.
/// </summary>
public static T FromXmlFile<T>(string filePath)
{
StreamReader sr = new StreamReader(filePath);
try
{
var result = FromXml<T>(sr.ReadToEnd());
return result;
}
catch (Exception e)
{
throw new Exception("There was an error attempting to read the file " + filePath + "\n\n" + e.InnerException.Message);
}
finally
{
sr.Close();
}
}
}
Example usage:
var result = XmlHelper.ToXml(userRecord);
Result:
<UserRecord>
<User>Username1</User>
<AliasRecords>
<AliasRecord>
<Alias>Alias1</Alias>
<Number>12345678</Number>
</AliasRecord>
<AliasRecord>
<Alias>Alias2</Alias>
<Number>23456789</Number>
</AliasRecord>
</AliasRecords>
</UserRecord>

Using XML files to store data in C#

I'm basically looking for someone to point me in the right direction on this. I read through some of the Microsoft documentation, but that wasn't very helpful. This is my first attempt at working with XML.
I'm writing an application that needs to store a list of known users and a list of aliases created by each of those users. I've figured out how to have my lists serialized and stored to XML files when the application closes and have it retrieve those when the application opens again, but I don't want to keep the list of users and aliases in memory.
In order for this to work, I need to have the ability to search, edit, and append to the XML file during run time.
The XML structure I envision is something like:
<UserRecord>
<User>Username-1</User>
<AliasRecord>
<Alias>Alias-1</Alias>
<Number>6135551234</Number>
</AliasRecord>
<AliasRecord>
<Alias>Alias-2</Alias>
<Number>6131238888</Number>
</AliasRecord>
</UserRecord>
Each user would only have one username but could have multiple aliases. I need to have the ability to add users, add aliases to a new or existing user, and change existing aliases. Usernames would never change, but an entire User record could be deleted.
So far, the only XML I've done in C# uses serialization but I don't think that approach will work for the above.
private void WriteXML()
{
try
{
System.Xml.Serialization.XmlSerializer XMLwriter = new System.Xml.Serialization.XmlSerializer(typeof(MessageRecord));
System.IO.StreamWriter XMLfile = new System.IO.StreamWriter("Saved MessageRecords.xml");
foreach (MessageRecord mr in OutgoingMessages)
{
XMLwriter.Serialize(XMLfile, mr);
}
XMLfile.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Create two classes to represent UserRecord and AliasRecord.
public class UserRecord
{
public string User { get; set; }
public List<AliasRecord> AliasRecords { get; set; }
}
public class AliasRecord
{
public string Alias { get; set; }
public string Number { get; set; }
}
Populate them like this:
var userRecord = new UserRecord
{
User = "UserName1",
AliasRecord = new List<AliasRecord> {
new AliasRecord { Alias = "Alias1", Number = "12345678" },
new AliasRecord { Alias = "Alias2", Number = "23456789" }
}
};
And use this code to serialize/deserialize it:
public static class XmlHelper
{
public static bool NewLineOnAttributes { get; set; }
/// <summary>
/// Serializes an object to an XML string, using the specified namespaces.
/// </summary>
public static string ToXml(object obj, XmlSerializerNamespaces ns)
{
Type T = obj.GetType();
var xs = new XmlSerializer(T);
var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };
var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, ws))
{
xs.Serialize(writer, obj, ns);
}
return sb.ToString();
}
/// <summary>
/// Serializes an object to an XML string.
/// </summary>
public static string ToXml(object obj)
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
return ToXml(obj, ns);
}
/// <summary>
/// Deserializes an object from an XML string.
/// </summary>
public static T FromXml<T>(string xml)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(xml))
{
return (T)xs.Deserialize(sr);
}
}
/// <summary>
/// Deserializes an object from an XML string, using the specified type name.
/// </summary>
public static object FromXml(string xml, string typeName)
{
Type T = Type.GetType(typeName);
XmlSerializer xs = new XmlSerializer(T);
using (StringReader sr = new StringReader(xml))
{
return xs.Deserialize(sr);
}
}
/// <summary>
/// Serializes an object to an XML file. (Fixed code)
/// </summary>
public static void ToXmlFile(object obj, string filePath)
{
var xs = new XmlSerializer(obj.GetType());
var ns = new XmlSerializerNamespaces();
var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };
ns.Add("", "");
using (XmlWriter writer = XmlWriter.Create(filePath, ws))
{
xs.Serialize(writer, obj, ns);
}
}
/// <summary>
/// Deserializes an object from an XML file.
/// </summary>
public static T FromXmlFile<T>(string filePath)
{
StreamReader sr = new StreamReader(filePath);
try
{
var result = FromXml<T>(sr.ReadToEnd());
return result;
}
catch (Exception e)
{
throw new Exception("There was an error attempting to read the file " + filePath + "\n\n" + e.InnerException.Message);
}
finally
{
sr.Close();
}
}
}
Example usage:
var result = XmlHelper.ToXml(userRecord);
Result:
<UserRecord>
<User>Username1</User>
<AliasRecords>
<AliasRecord>
<Alias>Alias1</Alias>
<Number>12345678</Number>
</AliasRecord>
<AliasRecord>
<Alias>Alias2</Alias>
<Number>23456789</Number>
</AliasRecord>
</AliasRecords>
</UserRecord>

write list of objects to a file

I've got a class salesman in the following format:
class salesman
{
public string name, address, email;
public int sales;
}
I've got another class where the user inputs name, address, email and sales.
This input is then added to a list
List<salesman> salesmanList = new List<salesman>();
After the user has input as many salesman to the list as they like, they have the option to save the list to a file of their choice (which I can limit to .xml or .txt(which ever is more appropriate)).
How would I add this list to the file?
Also this file needs to be re-read back into a list if the user wishes to later view the records.
Something like this would work. this uses a binary format (the fastest for loading) but the same code would apply to xml with a different serializer.
using System.IO;
[Serializable]
class salesman
{
public string name, address, email;
public int sales;
}
class Program
{
static void Main(string[] args)
{
List<salesman> salesmanList = new List<salesman>();
string dir = #"c:\temp";
string serializationFile = Path.Combine(dir, "salesmen.bin");
//serialize
using (Stream stream = File.Open(serializationFile, FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, salesmanList);
}
//deserialize
using (Stream stream = File.Open(serializationFile, FileMode.Open))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
List<salesman> salesman = (List<salesman>)bformatter.Deserialize(stream);
}
}
}
I just wrote a blog post on saving an object's data to Binary, XML, or Json; well writing an object or list of objects to a file that is. Here are the functions to do it in the various formats. See my blog post for more details.
Binary
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
XML
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
Json
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
Example
// Write the list of salesman objects to file.
WriteToXmlFile<List<salesman>>("C:\salesmen.txt", salesmanList);
// Read the list of salesman objects from the file back into a variable.
List<salesman> salesmanList = ReadFromXmlFile<List<salesman>>("C:\salesmen.txt");
If you want to use JSON then using Json.NET is usually the best way to go.
If for some reason you are unable to use Json.NET you can use the built in JSON support found in .NET.
You will need to include the following using statement and add a reference for System.Web.Extentsions.
using System.Web.Script.Serialization;
Then you would use these to Serialize and Deserialize your object.
//Deserialize JSON to your Object
YourObject obj = new JavaScriptSerializer().Deserialize<YourObject>("File Contents");
//Serialize your object to JSON
string sJSON = new JavaScriptSerializer().Serialize(YourObject);
https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer_methods(v=vs.110).aspx
If you want xml serialization, you can use the built-in serializer. To achieve this, add [Serializable] flag to the class:
[Serializable()]
class salesman
{
public string name, address, email;
public int sales;
}
Then, you could override the "ToString()" method which converts the data into xml string:
public override string ToString()
{
string sData = "";
using (MemoryStream oStream = new MemoryStream())
{
XmlSerializer oSerializer = new XmlSerializer(this.GetType());
oSerializer.Serialize(oStream, this);
oStream.Position = 0;
sData = Encoding.UTF8.GetString(oStream.ToArray());
}
return sData;
}
Then just create a method that writes this.ToString() into a file.
UPDATE
The mentioned above will serialize single entry as xml. If you need the whole list to be serialized, the idea would be a bit different. In this case you'd employ the fact that lists are serializable if their contents are serializable and use the serialization in some outer class.
Example code:
[Serializable()]
class salesman
{
public string name, address, email;
public int sales;
}
class salesmenCollection
{
List<salesman> salesmanList;
public void SaveTo(string path){
System.IO.File.WriteAllText (path, this.ToString());
}
public override string ToString()
{
string sData = "";
using (MemoryStream oStream = new MemoryStream())
{
XmlSerializer oSerializer = new XmlSerializer(this.GetType());
oSerializer.Serialize(oStream, this);
oStream.Position = 0;
sData = Encoding.UTF8.GetString(oStream.ToArray());
}
return sData;
}
}

Serialize and Deserialize object graph using BinaryFormatter

I'm trying to serialize my object graph to a string then deserialize it from a string. The object serializes just fine if I do this
using (var memStream = new System.IO.MemoryStream())
{
mf.Serialize(memStream, this);
memStream.Seek(0, 0);
Search s;
using (var memStrClone = new System.IO.MemoryStream())
{
memStream.CopyTo(memStrClone);
memStrClone.Seek(0, 0);
s = mf.Deserialize(memStrClone) as Search;
}
}
The above code works but serializing to a string and trying to deserialize that same string like this
Search s;
string xml = ToString<Search>(this);
s = FromString<Search>(xml);
public static TType FromString<TType>(string input)
{
var byteArray = Encoding.ASCII.GetBytes(input);
using (var stream = new MemoryStream(byteArray))
{
var bf = new BinaryFormatter();
return (TType)bf.Deserialize(stream);
}
}
public static string ToString<TType>(TType data)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, data);
return Encoding.ASCII.GetString(ms.GetBuffer());
}
}
Throws an exception
No assembly ID for object type '1936026741 Core.Sebring.BusinessObjects.Search.Search'.
Any help is greatly appreciated. Thanks.
Here is some code which will do what you want to to (I think) - but I've got to ask - why do you want to serialize to a string like that?
If the class is simple enough to serialise to a string, use an XML serializer which is much easier to deal with; if you want to serialize it out to disk, binary write it out to a file and if it is complicated and you are serializing it to transmit - consider using something like protobuf-net.
I think the crux of your problem is that you are trying to use ASCII encoding - I'm using Base64 encoding.
Anyway - here goes (I've just had a guess at your Search class!)
class Program
{
[Serializable]
public class Search
{
public Guid ID { get; private set; }
public Search() { }
public Search(Guid id)
{
ID = id;
}
public override string ToString()
{
return ID.ToString();
}
}
static void Main(string[] args)
{
Search search = new Search(Guid.NewGuid());
Console.WriteLine(search);
string serialized = SerializeTest.SerializeToString(search);
Search rehydrated = SerializeTest.DeSerializeFromString<Search>(serialized);
Console.WriteLine(rehydrated);
Console.ReadLine();
}
}
public class SerializeTest
{
public static Encoding _Encoding = Encoding.Unicode;
public static string SerializeToString(object obj)
{
byte[] byteArray = BinarySerializeObject(obj);
return Convert.ToBase64String(byteArray);
}
public static T DeSerializeFromString<T>(string input)
{
byte[] byteArray = Convert.FromBase64String(input);
return BinaryDeserializeObject<T>(byteArray);
}
/// <summary>
/// Takes a byte array and deserializes it back to its type of <see cref="T"/>
/// </summary>
/// <typeparam name="T">The Type to deserialize to</typeparam>
/// <param name="serializedType">The object as a byte array</param>
/// <returns>The deserialized type</returns>
public static T BinaryDeserializeObject<T>(byte[] serializedType)
{
if (serializedType == null)
throw new ArgumentNullException("serializedType");
if (serializedType.Length.Equals(0))
throw new ArgumentException("serializedType");
T deserializedObject;
using (MemoryStream memoryStream = new MemoryStream(serializedType))
{
BinaryFormatter deserializer = new BinaryFormatter();
deserializedObject = (T)deserializer.Deserialize(memoryStream);
}
return deserializedObject;
}
/// <summary>
/// Takes an object and serializes it into a byte array
/// </summary>
/// <param name="objectToSerialize">The object to serialize</param>
/// <returns>The object as a <see cref="byte"/> array</returns>
public static byte[] BinarySerializeObject(object objectToSerialize)
{
if (objectToSerialize == null)
throw new ArgumentNullException("objectToSerialize");
byte[] serializedObject;
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, objectToSerialize);
serializedObject = stream.ToArray();
}
return serializedObject;
}
}
HTH

Categories