0

我有两个课程:

 public class products
{
    public string category;
    public string name;
    public double price;
    public string desc;
    public string version;
    public string logoURL;
    public string imgURL;
    public string prod;

    public string Category
    {
        set { categorie = value; }
        get { return category; }
    }

和:

    [Serializable()]
public  class groupProducts
{
    public products[] produse;
}

我想对 groupProducts 类进行 XmlSerialize 并通过 TCP 连接将数据从服务器发送到客户端!我试过类似的东西:

   groupProducts gp = new groupProducts();
XmlSerializer xmlSel = new XmlSerializer(typeof(groupProducts));
TextWriter txtStream = new StreamWriter("xmlStreamFile.xml");    
xmlSel.Serialize(txtStream, gp); 
txtStream.Close();
try
{
Stream inputStream = File.OpenRead("xmlStreamFile.xml");
// declaring the size of the byte array to the length of the xmlfile
msg = new byte[inputStream.Length];
//storing the xml file in the byte array
inputStream.Read(msg, 0, (int)inputStream.Length);
//reading the byte array 
communicator[i].Send(msg);
}

但是当我在客户端反序列化它时 - XML 文件中有一些奇怪的数据!

你知道它会是什么吗?我究竟做错了什么?

4

1 回答 1

0

1-为了安全起见,我会在打开时使用编码StreamWriter

2- In inputStream.Read(msg, 0, (int)inputStream.Length);Read 不保证您会inputStream.Length从流中获取字节。您必须检查返回的值。

3-您不需要临时文件。采用MemoryStream

XmlSerializer xmlSel = new XmlSerializer(typeof(groupProducts));
MemoryStream m = new MemoryStream();
xmlSel.Serialize(m);
communicator[i].Send(m.ToArray());
于 2012-04-07T19:30:31.887 回答