using System; using System.Windows.Forms; using System.IO; using System.Text; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Binary;namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); private void button1_Click(object sender, EventArgs e) { string[,] str = new string[,] { { "1", "2", "ty","9i" }, { "3", "7", "0" ,"8"}, { "3", "7", "0","8"} }; BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(ms, str);
好像也可以序化存入对象
2.也是在我不知道第一种方式以前用的,将其存如varchar中,但要以特殊的分隔符格开如用','什么的,取时再以','分隔符截取
成数组
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private string m_strXML = ""; // 将二维数组序列化成XML
private void button1_Click(object sender, EventArgs e)
{
string[][] str = { new string[] { "1","2","3" }, new string[] { "A","B","C" } };
XmlSerializer xml = new XmlSerializer( str.GetType() );
System.IO.MemoryStream ms = new System.IO.MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, Encoding.Default);
xml.Serialize(writer, str); // 得到序列化后的XML字符串,可以直接保存到数据库
m_strXML = Encoding.Default.GetString(ms.ToArray());
MessageBox.Show(m_strXML);
} // 把XML反序列化为二维数组
private void button2_Click(object sender, EventArgs e)
{
// 从数据库取出XML字符串,这里使用m_strXML变量
XmlSerializer xml = new XmlSerializer( typeof(string[][]) );
StreamReader sr = new StreamReader(new MemoryStream(System.Text.Encoding.Default.GetBytes(m_strXML)), System.Text.Encoding.Default);
string[][] str=(string[][])xml.Deserialize(sr);
foreach (string[] s1 in str)
{
foreach (string s2 in s1)
{
MessageBox.Show(s2);
}
}
}
}
}
to:ZengHD
你的方法好啊
定义的二维数组 string[][] str我用到的是 string[,] List 这个格式,怎么统一呢?
真搞不懂这二个有啥区别
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} System.IO.MemoryStream ms = new System.IO.MemoryStream(); private void button1_Click(object sender, EventArgs e)
{
string[,] str = new string[,] { { "1", "2", "ty","9i" }, { "3", "7", "0" ,"8"}, { "3", "7", "0","8"} }; BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(ms, str);
// 把ms保存到数据库
} private void button2_Click(object sender, EventArgs e)
{
BinaryFormatter bFormatter = new BinaryFormatter();
ms.Position = 0;
string[,] str = (string[,])formater.Deserialize(ms) ;
// ms.Close(); for (int i = 0; i < str.GetLength(0); i++)
{
for (int j = 0; j < str.GetLength(1); j++)
{
MessageBox.Show(str[i,j]);
}
}
}
}
}
里面有个一个公共的转换对象到字节和字节到对象的方法http://hexun.com/zjysky