码迷,mamicode.com
首页 > 其他好文 > 详细

【转】DataTable保存与读取 stream

时间:2015-07-01 15:50:25      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

private void SaveToFile(byte[] value,string filePath)
{
    System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate);
    fs.Write(value, 0, value.Length); 
    fs.Flush(); 
    fs.Close(); 
}

private byte[] ConvertStreamToByteBuffer(string filePath)
{
    System.IO.Stream theStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    int b1;
    System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
    while ((b1 = theStream.ReadByte()) != -1)
    {
         tempStream.WriteByte(((byte)b1));
     }
    return tempStream.ToArray();
}         
public static byte[] GetsetBinary(DataTable dt)
{           
    byte[] bArrayResult = null; //用于存放序列化后的数据
    dt.RemotingFormat = SerializationFormat.Binary; //指定DataSet串行化格式是二进制
    MemoryStream ms = new MemoryStream();//定义内存流对象,用来存放DataSet序列化后的值
    IFormatter IF = new BinaryFormatter();//产生二进制序列化格式
    IF.Serialize(ms, dt);//串行化到内存中
    bArrayResult = ms.ToArray(); // 将DataSet转化成byte[]
    ms.Close();
    ms.Dispose();
    return bArrayResult;       
}       
public DataTable RetrieveDataSet(byte[] binaryData)
{           
    MemoryStream ms = new MemoryStream(binaryData);//创建内存流
    IFormatter bf = new BinaryFormatter();//产生二进制序列化格式
    object obj = bf.Deserialize(ms);//反串行化到内存中
    //类型检验
    ms.Close();
    if (obj is DataTable)
    {         
         DataTable dataSetResult = (DataTable)obj;
         return dataSetResult;
    }
    else
    {
          return null;
     }
}        
public static byte[] GetBytesByImage(System.Drawing.Image image)
{
     byte[] photo_byte = null;
     using (MemoryStream ms = new MemoryStream())
        {
            Bitmap bmp = new Bitmap(image);
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            photo_byte = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
            bmp.Dispose();
        }

    return photo_byte;
}            

//调用方法:


DataTable dt = DbHelperSQL.Query(sql);
DataTable newDt = dt.Clone();
newDt.Columns.Add("photo", System.Type.GetType("System.Byte[]"));
 foreach (DataRow dr in dt.Rows)
 {
       newDt.ImportRow(dr);
       System.Drawing.Image img = System.Drawing.Image.FromFile(StudentPhotoPath(dr["PhotoUrl"].ToString()));
       img = FixedSize(img, 135, 180);
       newDt.Rows[newDt.Rows.Count - 1]["photo"] = GetBytesByImage(img);
       img.Dispose();
}byte[] tableByteArray = GetsetBinary(newDt);
SaveToFile(tableByteArray, @"D:\hello.yzd");
byte[] byteArray = ConvertStreamToByteBuffer(@"D:\hello.yzd"); DataTable dt = RetrieveDataSet(byteArray);

 

【转】DataTable保存与读取 stream

标签:

原文地址:http://www.cnblogs.com/yzpopulation/p/4613169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!