C# XmlSerialize类并将其从客户端发送到服务器

C# XmlSerialize类并将其从客户端发送到服务器,c#,xml-serialization,client-server,C#,Xml Serialization,Client Server,我有两门课: 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 s

我有两门课:

 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; }
    }
以及:

我想对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文件中有一些奇怪的数据


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

1-为了安全起见,我会在打开
StreamWriter

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

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

XmlSerializer xmlSel = new XmlSerializer(typeof(groupProducts));
MemoryStream m = new MemoryStream();
xmlSel.Serialize(m);
communicator[i].Send(m.ToArray());

定义“奇怪的数据”。它仍然是有效的XML吗?是的,它仍然是XML数据,但只是其中的一部分!我已经设法纠正了它,但现在数据被写入了两次!我不知道那是什么意思。。。你能发布一些示例输出吗?例如Android,愤怒的小鸟,Android,愤怒的小鸟,你可以编辑你的答案,在另一边发布完整的XML。我怀疑缓冲或并行处理是这里的问题。也许按照LB的建议删除临时文件可以修复它,但可能不会。。。还不清楚什么是
communicator[i]
的类型以及Send()方法的作用-这些可能是问题的根源。请使用
MemoryStream
@IliaG上的
using
,这只是一个传统。MemoryStream没有任何可处置的资源。
XmlSerializer xmlSel = new XmlSerializer(typeof(groupProducts));
MemoryStream m = new MemoryStream();
xmlSel.Serialize(m);
communicator[i].Send(m.ToArray());