I'm trying to deserialize a bunch of data that was serialized by an old version of the code. When the data was serialized the classes had a different structure from the current class structure. To keep this data working in my new code, I hade to add the old classes structure to the code just for import this serialized data. I'm calling this classes as 'class'_oldVersions. To deserialize, I'm using this code:
className_oldVersions temp_className = new className_oldVersions();
XmlSerializer testSerializer = new XmlSerializer(typeof(className_oldVersions),
new XmlRootAttribute { ElementName = "className" });
temp_className = (ObservedData_OldVersions)testSerializer.Deserialize(ms_MemoryStream);
This code works fine, and I can deserialize the data using a diffent class name from the original. My problem is when I try to use this same procedure to deserialize an observable collection.
I created a code that reproduce my problem. In this code I serialize an observable collection of class OptimizationVariables and I would like to deserialize to an observable collection of class OptimizationVariablies_NewClass that has similar structure from the original one.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
public class OptimizationVariables
{
public string VariableName { get; set; }
}
public class OptimizationVariables_NewClass
{
public string VariableName { get; set; }
}
public class ModelsCollection
{
private ModelsCollection()
{
}
private ObservableCollection<OptimizationVariables> m_optimizationVariables =
new ObservableCollection<OptimizationVariables>();
public ObservableCollection<OptimizationVariables> OptimizationVariables
{
get { return m_optimizationVariables; }
set { m_optimizationVariables = value; }
}
private ObservableCollection<OptimizationVariables_NewClass> m_optimizationVariables_NewClass =
new ObservableCollection<OptimizationVariables_NewClass>();
public ObservableCollection<OptimizationVariables_NewClass> OptimizationVariables_NewClass
{
get { return m_optimizationVariables_NewClass; }
set { m_optimizationVariables_NewClass = value; }
}
}
class Program
{
static void Main(string[] args)
{
//Here I serialize an ObservableCollection of 2 OptimizationVariables instances
Serialize();
//Here I deserialize for the same class and works fine
Deserialize();
//Here I try to deserialize to a new class with same structure, but different name. I a have an error.
Deserialize2NewClass();
}
static void Serialize()
{
MemoryStream ms;
ObservableCollection<OptimizationVariables> OptimizationVariables2Serialize = new ObservableCollection<OptimizationVariables>();
OptimizationVariables opt_var1 = new OptimizationVariables();
opt_var1.VariableName = "Variable Name 1";
OptimizationVariables2Serialize.Add(opt_var1);
OptimizationVariables opt_var2 = new OptimizationVariables();
opt_var1.VariableName = "Variable Name 2";
OptimizationVariables2Serialize.Add(opt_var1);
ms = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<OptimizationVariables>));
serializer.Serialize(ms, OptimizationVariables2Serialize);
TextWriter sw = new StreamWriter("XML_File_x64.bin");
sw.WriteLine(Convert.ToBase64String(ms.ToArray()));
sw.Close();
}
static void Deserialize()
{
byte[] memoryData;
MemoryStream ms;
TextReader sw = new StreamReader("XML_File_x64.bin");
memoryData = Convert.FromBase64String(sw.ReadLine());
ms = new MemoryStream(memoryData);
ObservableCollection<OptimizationVariables> OptimizationVariablesDeserialized = new ObservableCollection<OptimizationVariables>();
XmlSerializer deserializer = new XmlSerializer(typeof(ObservableCollection<OptimizationVariables>));
OptimizationVariablesDeserialized = (ObservableCollection<OptimizationVariables>)deserializer.Deserialize(ms);
Console.Write(OptimizationVariablesDeserialized.Count());
sw.Close();
}
static void Deserialize2NewClass()
{
byte[] memoryData;
MemoryStream ms;
TextReader sw = new StreamReader("XML_File_x64.bin");
memoryData = Convert.FromBase64String(sw.ReadLine());
ms = new MemoryStream(memoryData);
ObservableCollection<OptimizationVariables_NewClass> OptimizationVariablesDeserialized = new ObservableCollection<OptimizationVariables_NewClass>();
XmlSerializer deserializer = new XmlSerializer(typeof(ObservableCollection<OptimizationVariables_NewClass>));
OptimizationVariablesDeserialized = (ObservableCollection<OptimizationVariables_NewClass>)deserializer.Deserialize(ms);
Console.Write(OptimizationVariablesDeserialized.Count());
sw.Close();
}
}
The problem in your code is that the class OptimizationVariables name is saved in the xml data when serializing. but for deserialization it expects a OptimizationVariables_NewClass name which is not within the xml file.
consider the fact that not only the variable names, but also the class names will be used when serializing a class or struct...
So, just changed your code to make it save the data in readable xml file, then replacing "OptimizationVariables" with "OptimizationVariables_NewClass" solved the error:
using System;
using System.Linq;
using System.IO;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
public class OptimizationVariables
{
public string VariableName { get; set; }
}
public class OptimizationVariables_NewClass
{
public string VariableName { get; set; }
}
public class ModelsCollection
{
private ModelsCollection()
{
}
private ObservableCollection<OptimizationVariables> m_optimizationVariables =
new ObservableCollection<OptimizationVariables>();
public ObservableCollection<OptimizationVariables> OptimizationVariables
{
get { return m_optimizationVariables; }
set { m_optimizationVariables = value; }
}
private ObservableCollection<OptimizationVariables_NewClass> m_optimizationVariables_NewClass =
new ObservableCollection<OptimizationVariables_NewClass>();
public ObservableCollection<OptimizationVariables_NewClass> OptimizationVariables_NewClass
{
get { return m_optimizationVariables_NewClass; }
set { m_optimizationVariables_NewClass = value; }
}
}
class Program
{
static void Main(string[] args)
{
Serialize();
Deserialize();
Deserialize2NewClass();
}
static void Serialize()
{
ObservableCollection<OptimizationVariables> OptimizationVariables2Serialize = new ObservableCollection<OptimizationVariables>();
OptimizationVariables opt_var1 = new OptimizationVariables();
opt_var1.VariableName = "Variable Name 1";
OptimizationVariables2Serialize.Add(opt_var1);
OptimizationVariables opt_var2 = new OptimizationVariables();
opt_var1.VariableName = "Variable Name 2";
OptimizationVariables2Serialize.Add(opt_var1);
TextWriter writer = new StreamWriter("XML_File.xml");
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<OptimizationVariables>));
serializer.Serialize(writer, OptimizationVariables2Serialize);
writer.Close();
}
static void Deserialize()
{
TextReader sw = new StreamReader("XML_File.xml");
ObservableCollection<OptimizationVariables> OptimizationVariablesDeserialized = new ObservableCollection<OptimizationVariables>();
XmlSerializer deserializer = new XmlSerializer(typeof(ObservableCollection<OptimizationVariables>));
OptimizationVariablesDeserialized = (ObservableCollection<OptimizationVariables>)deserializer.Deserialize(sw);
Console.Write(OptimizationVariablesDeserialized.Count());
sw.Close();
}
static void Deserialize2NewClass()
{
TextReader sw = new StreamReader("XML_File.xml");
var str = sw.ReadToEnd();
sw.Close();
str = str.Replace("OptimizationVariables", "OptimizationVariables_NewClass");
var stream = new StringReader(str);
ObservableCollection<OptimizationVariables_NewClass> OptimizationVariablesDeserialized = new ObservableCollection<OptimizationVariables_NewClass>();
XmlSerializer deserializer = new XmlSerializer(typeof(ObservableCollection<OptimizationVariables_NewClass>));
OptimizationVariablesDeserialized = (ObservableCollection<OptimizationVariables_NewClass>)deserializer.Deserialize(stream);
Console.Write(OptimizationVariablesDeserialized.Count());
}
}
now it works fine!
Related
I try to save an object to an XML Document.
I always get an inner Exception Error.
I think it has to do something with boxing and unboxing but i cannot help myself.
So here we go:
The Method for XML Saving
public class Saveclass
//
public static void Save(string filename, List<Class> classlist)
{
StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8);
XmlSerializer serializer = new XmlSerializer(typeof(class));
serializer.Serialize(writer,classlist);//Here i get the error at classlist
writer.Close();
}
And here the SaveFile Dialog
private void SaveButton(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "XML Data|*.xml";
if (dialog.ShowDialog() == DialogResult.OK)
{
List<class> classlist = null;
foreach (ListViewItem item in this.listViewWinforms.Items)
{
classlist = new List<class>();
}
Saveclass.Save(dialog.FileName, classlist)
}
}
In the Basic i have a Listview with Items inside and want to save these Items in my listview to an XML Document
Error is
System.InvalidOperationException: 'Trying to generate an XML Document
InvalidCastException: The object of the Type "System.Collections.Generic.List`1[Namespace.Class]" cannot cast into"Namespace.Class"
There is a type mismatch.
You are defining your serializer as:
new XmlSerializer(typeof(class));
Which is configured to serialize objects of type class.
However, you are then trying to serialize the classlist object, which is not a class but a List<Class>.
Try defining your serializer as:
new XmlSerializer(typeof(List<Class>));
By the way, naming your class class is very confusing. You should try to name your classes more descriptively.
I think you need to change just one line:
Just use typeof(List) instead of typeof(class))
XmlSerializer serializer = new XmlSerializer(typeof(List<Class>));
Here is a small example
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
List<Car> myList = new List<Car>();
myList.Add(new Car(){ Name = "Beetle", Brand = "VW", Price = 5999.9M });
myList.Add(new Car(){ Name = "Corolla", Brand = "Toyota", Price = 49999.9M });
Saveclass.Save("carlist.xml",myList);
}
}
public static class Saveclass
{
public static void Save(string filename, List<Car> classlist)
{
StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8);
XmlSerializer serializer = new XmlSerializer(typeof(List<Car>));
serializer.Serialize(writer,classlist);
writer.Close();
}
}
public class Car
{
public string Name {get;set;}
public string Brand {get; set;}
public decimal Price {get; set;}
}
}
You can test here
I would like to deserialize part of xml, I tried this, but it does not work.
class Program
{
static void Main(string[] args)
{
var serializer = new XmlSerializer(typeof(Test), new XmlRootAttribute("Test"));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("<Root1><Root2><Test><Id>5</Id></Test></Root2></Root1>")))
{
var test = serializer.Deserialize(stream);
}
}
}
public class Test
{
public int Id;
}
How can I say to XmlSerializer to start serialization from <Test>?
Move to desired node with XmlReader.
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("<Root1><Root2><Test><Id>5</Id></Test></Root2></Root1>")))
using (var reader = XmlReader.Create(stream))
{
reader.ReadToFollowing("Test");
var test = (Test)serializer.Deserialize(reader);
}
How can i serialize Instance of College to XML using Linq?
class College
{
public string Name { get; set; }
public string Address { get; set; }
public List<Person> Persons { get; set; }
}
class Person
{
public string Gender { get; set; }
public string City { get; set; }
}
You can't serialize with LINQ. You can use XmlSerializer.
XmlSerializer serializer = new XmlSerializer(typeof(College));
// Create a FileStream to write with.
Stream writer = new FileStream(filename, FileMode.Create);
// Serialize the object, and close the TextWriter
serializer.Serialize(writer, i);
writer.Close();
Not sure why people are saying you can't serialize/deserialize with LINQ. Custom serialization is still serialization:
public static College Deserialize(XElement collegeXML)
{
return new College()
{
Name = (string)collegeXML.Element("Name"),
Address = (string)collegeXML.Element("Address"),
Persons = (from personXML in collegeXML.Element("Persons").Elements("Person")
select Person.Deserialize(personXML)).ToList()
}
}
public static XElement Serialize(College college)
{
return new XElement("College",
new XElement("Name", college.Name),
new XElement("Address", college.Address)
new XElement("Persons", (from p in college.Persons
select Person.Serialize(p)).ToList()));
);
Note, this probably isn't the greatest approach, but it's answering the question at least.
You can't use LINQ. Look at the below code as an example.
// This is the test class we want to
// serialize:
[Serializable()]
public class TestClass
{
private string someString;
public string SomeString
{
get { return someString; }
set { someString = value; }
}
private List<string> settings = new List<string>();
public List<string> Settings
{
get { return settings; }
set { settings = value; }
}
// These will be ignored
[NonSerialized()]
private int willBeIgnored1 = 1;
private int willBeIgnored2 = 1;
}
// Example code
// This example requires:
// using System.Xml.Serialization;
// using System.IO;
// Create a new instance of the test class
TestClass TestObj = new TestClass();
// Set some dummy values
TestObj.SomeString = "foo";
TestObj.Settings.Add("A");
TestObj.Settings.Add("B");
TestObj.Settings.Add("C");
#region Save the object
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass));
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(#"C:\test.xml");
SerializerObj.Serialize(WriteFileStream, TestObj);
// Cleanup
WriteFileStream.Close();
#endregion
/*
The test.xml file will look like this:
<?xml version="1.0"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeString>foo</SomeString>
<Settings>
<string>A</string>
<string>B</string>
<string>C</string>
</Settings>
</TestClass>
*/
#region Load the object
// Create a new file stream for reading the XML file
FileStream ReadFileStream = new FileStream(#"C:\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
// Load the object saved above by using the Deserialize function
TestClass LoadedObj = (TestClass)SerializerObj.Deserialize(ReadFileStream);
// Cleanup
ReadFileStream.Close();
#endregion
// Test the new loaded object:
MessageBox.Show(LoadedObj.SomeString);
foreach (string Setting in LoadedObj.Settings)
MessageBox.Show(Setting);
you have to use the XML serialization
static public void SerializeToXML(College college)
{
XmlSerializer serializer = new XmlSerializer(typeof(college));
TextWriter textWriter = new StreamWriter(#"C:\college.xml");
serializer.Serialize(textWriter, college);
textWriter.Close();
}
You can use that if you needed XDocument object after serialization
DataClass dc = new DataClass();
XmlSerializer x = new XmlSerializer(typeof(DataClass));
MemoryStream ms = new MemoryStream();
x.Serialize(ms, dc);
ms.Seek(0, 0);
XDocument xDocument = XDocument.Load(ms); // Here it is!
I'm not sure if that is what you want, but to make an XML-Document out of this:
College coll = ...
XDocument doc = new XDocument(
new XElement("College",
new XElement("Name", coll.Name),
new XElement("Address", coll.Address),
new XElement("Persons", coll.Persons.Select(p =>
new XElement("Person",
new XElement("Gender", p.Gender),
new XElement("City", p.City)
)
)
)
);
I have read many codes on this but none happened to solve the problem. first the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Serialization
{
class Program
{
static void Main(string[] args)
{
using (MoveSaver objSaver = new MoveSaver(#"C:\1.bin"))
{
MoveAndTime mv1, mv2;
mv1.MoveStruc = "1";
mv1.timeHLd = DateTime.Now;
objSaver.SaveToFile(mv1);
mv2.MoveStruc = "2";
mv2.timeHLd = DateTime.Now;
objSaver.SaveToFile(mv2);
}
using (MoveSaver svrObj = new MoveSaver())
{
MoveAndTime[] MVTobjs = svrObj.DeSerializeObject(#"C:\1.bin");
foreach (MoveAndTime item in MVTobjs)
{
//Do Something
}
}
}
}
public class MoveSaver:IDisposable
{
public void Dispose()
{
if (fs != null)
{
fs.Close();
}
}
FileStream fs;
StreamWriter sw;
public string filename { get; set; }
public MoveSaver(string FileName)
{
this.filename = FileName;
fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
}
public MoveSaver()
{
}
~MoveSaver()
{
if (fs != null)
{
fs.Close();
}
}
public MoveAndTime[] DeSerializeObject(string filename)
{
MoveAndTime[] objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize = (MoveAndTime[])bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
public bool SaveToFile(MoveAndTime moveTime)
{
try
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(fs, moveTime);
return true;
}
catch (Exception)
{
return false;
}
}
}
[Serializable]
public struct MoveAndTime
{
public string MoveStruc;
public DateTime timeHLd;
}
}
The code mimics a need for saving all actions of user on the program. to be later shown on that program (say you play cards or so and you want to review :D what has happened). The problem is when DeSerializeObject function is called the line objectToSerialize = (MoveAndTime[])bFormatter.Deserialize(stream); throws an exception (definitely in runtime) that the cast from a single object to array is not valid:
Unable to cast object of type
'Serialization.MoveAndTime' to type
'Serialization.MoveAndTime[]'.
Any idea? Any improvement or total change of approach is appreciated.
You're saving a single MoveAndTime instance to the file, but you're trying to read an array of them.
Please modify your main block like this. I think it achieves what you want.
static void Main(string[] args)
{
using (MoveSaver objSaver = new MoveSaver(#"C:\1.bin"))
{
MoveAndTime[] MVobjects = new MoveAndTime[2];
MoveAndTime mv1, mv2;
mv2 = new MoveAndTime();
mv1 = new MoveAndTime();
mv1.MoveStruc = "1";
mv1.timeHLd = DateTime.Now;
mv2.MoveStruc = "2";
mv2.timeHLd = DateTime.Now;
MVobjects[0] = new MoveAndTime();
MVobjects[0] = mv1;
MVobjects[1] = new MoveAndTime();
MVobjects[1] = mv2;
objSaver.SaveToFile(MVobjects);
}
using (MoveSaver svrObj = new MoveSaver())
{
MoveAndTime[] MVTobjs = svrObj.DeSerializeObject(#"C:\1.bin");
foreach (MoveAndTime item in MVTobjs)
{
//Do Something
Console.WriteLine(item.MoveStruc);
Console.WriteLine(item.timeHLd);
}
}
}
Thanks
If I create a class in C#, how can I serialize/deserialize it to a file? Is this somethat that can be done using built in functionality or is it custom code?
XmlSerializer; note that the exact xml names can be controlled through various attributes, but all you really need is:
a public type
with a default constructor
and public read/write members (ideally properties)
Example:
using System;
using System.Xml;
using System.Xml.Serialization;
public class Person {
public string Name { get; set; }
}
static class Program {
static void Main() {
Person person = new Person { Name = "Fred"};
XmlSerializer ser = new XmlSerializer(typeof(Person));
// write
using (XmlWriter xw = XmlWriter.Create("file.xml")) {
ser.Serialize(xw, person);
}
// read
using (XmlReader xr = XmlReader.Create("file.xml")) {
Person clone = (Person) ser.Deserialize(xr);
Console.WriteLine(clone.Name);
}
}
}
You need to use class XmlSerializer. Main methods are Serialize and Deserialize. They accept streams, text readers\writers and other classes.
Code sample:
public class Program
{
public class MyClass
{
public string Name { get; set; }
}
static void Main(string[] args)
{
var myObj = new MyClass { Name = "My name" };
var fileName = "data.xml";
var serializer = new XmlSerializer(typeof(MyClass));
using (var output = new XmlTextWriter(fileName, Encoding.UTF8))
serializer.Serialize(output, myObj);
using (var input = new StreamReader(fileName))
{
var deserialized = (MyClass)serializer.Deserialize(input);
Console.WriteLine(deserialized.Name);
}
Console.WriteLine("Press ENTER to finish");
Console.ReadLine();
}
}