Xml序列化类并将其从客户端发送到服务器
本文关键字:客户端 服务器 序列化 Xml | 更新日期: 2023-09-27 18:30:16
我有 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-为了安全起见,我会在打开StreamWriter
时使用编码
2-在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());