記憶體流MemoryStream及序列化測試!

來源:互聯網
上載者:User
 1 using System;
 2 using System.Data;
 3 using System.Data.SqlClient;
 4 using System.IO;
 5 using System.Runtime.Serialization.Formatters;
 6 using System.Runtime.Serialization.Formatters.Soap;
 7 using System.Runtime.Serialization.Formatters.Binary;
 8 using System.Xml.Serialization;
 9 namespace ConsoleApplication1
10 {
11     /// <summary>
12     /// Class1 的摘要說明。
13     /// </summary>
14     class Class1
15     {
16         /// <summary>
17         /// 應用程式的主進入點。
18         /// </summary>
19         [STAThread]
20         static void Main(string[] args)
21         {
22             System.Data.SqlClient.SqlConnection connection=new System.Data.SqlClient.SqlConnection
23                 ("Server=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
24             System.Data.SqlClient.SqlDataAdapter myda=new System.Data.SqlClient.SqlDataAdapter
25                 ("select * from customers",connection);
26             System.Data.DataSet myds=new System.Data.DataSet();
27             System.Data.DataSet myds2=new System.Data.DataSet();
28             myda.Fill(myds,"Customers");
29             System.IO.MemoryStream s=new System.IO.MemoryStream();
30             SoapFormatter sf=new SoapFormatter();
31             sf.Serialize(s,myds);
32             s.Seek(0,SeekOrigin.Begin);
33             //或者
34             MemoryStream s1=new MemoryStream(s.ToArray(),true);
35             myds2=(DataSet)sf.Deserialize(s);
36             Console.WriteLine(myds2.GetXmlSchema());
37             Console.WriteLine("");
38             myds2=(DataSet)sf.Deserialize(s1);
39             Console.WriteLine(myds2.GetXmlSchema());
40             s.Close();
41             //實驗直接得到字串的形式
42             string s3=System.Text.UTF8Encoding.UTF8.GetString(s1.ToArray());
43             Console.WriteLine(s3);
44             s1.Close();
45 
46         }
47     }
48 }
49 
50 還有其它序列化,包括XML序列化,Binary序列化,基本方式都是一樣的.
51 另外,還可以序列化到本地檔案中.放在記憶體中就可以在諸如Socket的程式中發送了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.