I am facing this problem
class person
{
;
}
person p = new person();
XmlSerializer ser = new XmlSerializer(p.GetType());
FileStream fs = File.Open("sam.xml",FileMode.OpenOrCreate, FileAccess.Write);
ser.Serialize(fs,p)
fs.flush();
fs.close();
FileStream stream = FileStream("sam.xml", FileMode.Open);
XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream,new XmlDictionaryReaderQuotas());
now my problem is how can i create xdr object without creating xml files.
You can do it with a memory stream like that:
class person
{
;
}
person p = new person();
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer ser = new XmlSerializer(p.GetType());
ser.Serialize(ms,p)
ms.Seek(0, SeekOrigin.Begin);
XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(ms,new XmlDictionaryReaderQuotas());
}
That should work.
Serialize to a memorystream instead of a filestream.
Related
I had an ASP.net app in which we serialized a string content using BinaryFormatter like this :
BinaryFormatter bf = new BinaryFormatter();
try
{
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, Content);
var SerializedContent = ms.GetBuffer();
return SerializedContent;
}
// ...
But now that BinaryFormatter has become obsolete I am getting exception. I have been trying to use XMLSerializer but haven't been able to make it work. This is what I have been trying:
XmlSerializer xmlSerializer = new XmlSerializer(Content.GetType());
using (MemoryStream ms = new MemoryStream())
{
xmlSerializer.Serialize(ms, Content);
var SerializedContent = ms.GetBuffer();
return SerializedContent;
}
// ...
But I don't get the correct output. What am I doing wrong?
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);
}
}
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream m = new MemoryStream())
{
formatter.Serialize(m, list);
StreamReader sr = new StreamReader(m);
HiddenField1.Value = sr.ReadToEnd();
}
i'm getting a blank value for HiddenField1.Value. Not sure what I'm doing is even possible? list is definitely populated (is a List<T>)
Depending on what you want to achieve... One option is to show content of the binary stream as Base64 string:
var memoryStream = new MemoryStream();
using(memoryStream)
{
formatter.Serialize(memoryStream, list);
}
HiddenField1.Value = Convert.ToBase64String(memoryStream.ToArray());
Change it to:
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream m = new MemoryStream())
{
formatter.Serialize(m, list);
m.Position = 0;
StreamReader sr = new StreamReader(m);
HiddenField1.Value = sr.ReadToEnd();
}
You need to reset the position of the stream back to the beginning before reading it. Also, you shouldn't use StreamReader to convert a binary stream like this to text, because it will break in unexpected ways. If you want the results in a text-like format, use Convert.ToBase64String as in #Alexei's answer.
My method returns Dictionary<TZerokey, Dictionary<TFirstKey, Dictionary<TSecondKey,Dictionary<TThirdKey,TValue>>>> and i would to serialise/deserialise this object as XML using DataContractSerialiser.
Below are my methods:
public static void SerializeDictionaryToXml<T>(this T obj, string fileName)
{
DataContractSerializer ser = new DataContractSerializer(typeof(T));
// System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
FileStream fileStream = new FileStream(fileName, FileMode.Create);
ser.WriteObject(fileStream, obj);
fileStream.Close();
}
public static T DeserializeDictionaryFromXml<T>(string xml)
{
FileStream fs = new FileStream(xml,
FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(T));
// Deserialize the data and read it from the instance.
T deserializedObject = (T)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
return deserializedObject;
}
The code runs fine except that I do not get the expected output. Can someone see what I'm doing wrong?
The following code sample shows how to serialize/deserialize to a file. How could I modify this to serialize to a variable instead of to a file? (Assume the variable would be passed in to the read/write methods instead of a file name).
public static void WriteObject(string fileName)
{
Console.WriteLine(
"Creating a Person object and serializing it.");
Person p1 = new Person("Zighetti", "Barbara", 101);
FileStream writer = new FileStream(fileName, FileMode.Create);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
writer.Close();
}
public static void ReadObject(string fileName)
{
Console.WriteLine("Deserializing an instance of the object.");
FileStream fs = new FileStream(fileName,
FileMode.Open);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person deserializedPerson =
(Person)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
Console.WriteLine(String.Format("{0} {1}, ID: {2}",
deserializedPerson.FirstName, deserializedPerson.LastName,
deserializedPerson.ID));
}
You can change the FileStream to a memory stream and dump it to a byte[].
public static byte[] WriteObject<T>(T thingToSave)
{
Console.WriteLine("Serializing an instance of the object.");
byte[] bytes;
using(var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, thingToSave);
bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(bytes, 0, (int)stream.Length);
}
return bytes;
}
public static T ReadObject<T>(byte[] data)
{
Console.WriteLine("Deserializing an instance of the object.");
T deserializedThing = default(T);
using(var stream = new MemoryStream(data))
using(var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
{
var serializer = new DataContractSerializer(typeof(T));
// Deserialize the data and read it from the instance.
deserializedThing = (T)serializer.ReadObject(reader, true);
}
return deserializedThing;
}