昨天說了DataSet的序列化及壓縮,今天把解壓縮及反序列化的代碼寫一下:
view plaincopy to clipboardPRint?
/// <summary>
/// 反序列化壓縮的DataSet
/// </summary>
/// <param name="_filePath"></param>
/// <returns></returns>
static DataSet DataSetDeserializeDecompress(string _filePath)
{
FileStream fs = File.OpenRead(_filePath);//打開文件
fs.Position = 0;//設置文件流的位置
GZipStream gzipStream = new GZipStream(fs, CompressionMode.Decompress);//創建解壓對象
byte[] buffer = new byte[4096];//定義數據緩沖
int offset = 0;//定義讀取位置
MemoryStream ms = new MemoryStream();//定義內存流
while ((offset = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, offset);//解壓后的數據寫入內存流
}
BinaryFormatter sfFormatter = new BinaryFormatter();//定義BinaryFormatter以反序列化DataSet對象
ms.Position = 0;//設置內存流的位置
DataSet ds;
try
{
ds = (DataSet)sfFormatter.Deserialize(ms);//反序列化
}
catch
{
throw;
}
finally
{
ms.Close();//關閉內存流
ms.Dispose();//釋放資源
}
fs.Close();//關閉文件流
fs.Dispose();//釋放資源
gzipStream.Close();//關閉解壓縮流
gzipStream.Dispose();//釋放資源
return ds;
}
/// <summary>
/// 反序列化未壓縮的DataSet
/// </summary>
/// <param name="_filePath"></param>
/// <returns></returns>
static DataSet DataSetDeserialize(string _filePath)
{
FileStream fs = File.OpenRead(_filePath);//打開文件
fs.Position = 0;//設置文件流的位置
BinaryFormatter sfFormatter = new BinaryFormatter();//定義BinaryFormatter以反序列化DataSet對象
DataSet ds;
try
{
ds = (DataSet)sfFormatter.Deserialize(fs);//反序列化
}
catch
{
throw;
}
finally
{
fs.Close();//關閉內存流
fs.Dispose();//釋放資源
}
fs.Close();//關閉文件流
fs.Dispose();//釋放資源
return ds;
}
http://blog.csdn.net/wlkjhxd/archive/2009/03/25/4022544.aspx
新聞熱點
疑難解答