我有完全相同的要求从 CRM FetchRequest 保存原始 EntityCollection 响应。我从标准 XmlSerializer 中得到了与您相同的结果,诀窍是使用 CRM 在后台使用的相同序列化程序。
看一下 DataContractSerializer 类:MSDN 参考在这里
这是我最后写的助手类:
class Serialiser
{
/// <summary>
/// The xml serialiser instance.
/// </summary>
private readonly DataContractSerializer dataContractSerialiser;
/// <summary>
/// Initializes a new instance of the <see cref="SerialiserService.Serialiser"/> class.
/// </summary>
/// <param name="typeToSerilaise">The type to serilaise.</param>
public Serialiser(Type typeToSerilaise)
{
this.dataContractSerialiser = new DataContractSerializer(typeToSerilaise);
}
/// <summary>
/// Serialises the specified candidate.
/// </summary>
/// <param name="candidate">The candidate.</param>
/// <returns>A serialised representaiton of the specified candidate.</returns>
public byte[] Serialise(object candidate)
{
byte[] output;
using (var ms = new MemoryStream())
{
this.dataContractSerialiser.WriteObject(ms, candidate);
var numberOfBytes = ms.Length;
output = new byte[numberOfBytes];
// Note: Only copy the exact stream length to avoid capturing trailing null bytes.
Array.Copy(ms.GetBuffer(), output, numberOfBytes);
}
return output;
}
/// <summary>
/// Deserialises the specified serialised instance.
/// </summary>
/// <param name="serialisedInstance">The serialised instance.</param>
/// <returns>A deserialised instance of the specified type.</returns>
public object Deserialise(byte[] serialisedInstance)
{
object output;
using (var ms = new MemoryStream(serialisedInstance))
using (var reader = XmlDictionaryReader.CreateTextReader(ms, new XmlDictionaryReaderQuotas()))
{
output = this.dataContractSerialiser.ReadObject(reader);
}
return output;
}
}
用法:
new Serialiser(typeof(EntityCollection));
然后,您可以读取或写入 byte[] 到磁盘。