DataTable保存与读取 stream

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)