簡體   English   中英

XmlSerialize 一個 class 並將其從客戶端發送到服務器

[英]XmlSerialize a class and send it from client to 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 class 並通過 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); Read 不保證您將從 stream 獲得inputStream.Length字節。您必須檢查返回值。

3-您不需要臨時文件。 使用MemoryStream

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM