I am developing a WCF service which will be consumed by multiple different client applications. In order to make one functionality work, the server needs to read an XML file into a C# DataContract which is then passed on to the concerned client. As far as I understand from the MSDN website, this is possible but I couldn't find any complete examples. In particular, the website talks about a 'stream' parameter which I don't quite get yet.
My data contract has one property field which is a list of another data contract which has multiple simple property fields.
e.g.
[DataContract]
public class MyClass1 {
[DataMember]
public string name;
[DataMember]
public int age;
}
[DataContract]
public class MyClass2 {
[DataMember]
public List<MyClass1> myClass1List;
}
My classes look something like this.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
We create the object “stream” to open the file Example. txt in reading only mode. We then use the formatter class which is used to deserialize the object, which is stored in the Example. txt file.
Here is an example
MyClass1 obj = new MyClass1();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass1));
using (Stream stream = new FileStream(@"C:\tmp\file.xml", FileMode.Create, FileAccess.Write))
{
using (XmlDictionaryWriter writer =
XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
{
writer.WriteStartDocument();
dcs.WriteObject(writer, obj);
}
}
Books b = new Books();
DataContractSerializer dcs = new DataContractSerializer(typeof(Books));
try
{
Stream fs = new FileStream(@"C:\Users\temelm\Desktop\XmlFile.xml", FileMode.Create, FileAccess.Write);
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(fs, Encoding.UTF8);
xdw.WriteStartDocument();
dcs.WriteObject(xdw, b);
xdw.Close();
fs.Flush();
fs.Close();
}
catch (Exception e)
{
s += e.Message + "\n";
}
This can be useful for you. When you need XElement. For instance when you going append node to XDocument or replece XElement of this document.
private XElement objectToXElement(SomeContractType obj)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(SomeContractType);
var ms = new MemoryStream();
var xw = XmlWriter.Create(ms);
dcs.WriteObject(xw, obj);
xw.Flush();
xw.Close();
ms.Position = 0;
XElement xe = XElement.Load(ms);
return xe;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With