XmlSerializer formatter = new XmlSerializer(typeof(List<Objects.PIP>));
**MemoryStream stream = new MemoryStream(new byte[1024]);**
formatter.Serialize(stream, Repository.GlobalRepository.PIPInformation);
byte[] bt = stream.ToArray();
foreach (Communication.Client Client in server.ClientList)
{
Client.SendMessage(bt);
}
stream.Flush();
我在 stared line 中收到一个错误:
There was an error generating the XML document.
InnerException {"Memory stream is not expandable."}
PIP Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectLibrary.Model;
using System.Xml.Serialization;
namespace PIPServer.Objects
{
[XmlRoot(Namespace = "urn:my-namespace")]
public class PIP
{
private long pipID;
public long PipID
{
get { return pipID; }
set { pipID = value; }
}
private CurrencyPair currencyPair;
public CurrencyPair CurrencyPair
{
get { return currencyPair; }
set { currencyPair = value; }
}
...............
}
}
我做错了什么? 我将 Stream 转换为字节数组的方法是否正确? [已回答]
请您参考如下方法:
MemoryStream 有一个您可以使用的 ToArray() 方法。它返回一个包含流的全部内容的字节数组。只需确保在读取内容之前已完成写入流。 :-)
至于错误,没有更多信息很难回答。您是否已验证您尝试序列化的所有对象均有效?
编辑:
从您的评论中,我想我知道问题出在哪里。您定义了固定大小为 1024 字节的 MemoryStream。当你序列化你的对象时,生成的 xml 比那个大,你最终会得到一个错误,说你不能扩展内存流。尝试在不设置明确大小的情况下创建它(只需使用
new MemoryStream()
),或设置更大的尺寸。
此外,如果您不想序列化某个属性,只需使用 XmlIgnore 属性对其进行标记即可。
