XmlSerialize一个类并将其从客户端发送到服务器

时间:2012-04-07 19:23:00

标签: c# xml-serialization client-server

我有2个分支:

 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;
}

我想XmlSerialize groupProducts类,并通过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文件中有一些奇怪的数据!

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

1 个答案:

答案 0 :(得分: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());