对于需要频繁访问的数据,可以在用户第一次访问该数据的时候将其序列化为本地文件,这样,用户再次访问该数据的时候就无需再次访问数据库,而是直接将本地文件反序列化为数据集,这样能大大的优化系统的性能。
实现序列化和反序列化的类:
1
using
System;
2 using System.Data;
3 using System.Configuration;
4 using System.Web;
5 using System.Web.Security;
6 using System.Web.UI;
7 using System.Web.UI.WebControls;
8 using System.Web.UI.WebControls.WebParts;
9 using System.Web.UI.HtmlControls;
10 using System.Runtime.Serialization;
11 using System.IO;
12 using System.Runtime.Serialization.Formatters.Binary;
13
14 /// <summary>
15 /// Summary description for FileIO
16 /// </summary>
17 public class FileIO < T >
18 {
19 public void Serialize(T items, string sFile)
20 {
21 IFormatter formatter = new BinaryFormatter();
22
23 Stream stream = new FileStream(HttpContext.Current.Server.MapPath(sFile), FileMode.Create,
24 FileAccess.Write, FileShare.None);
25 formatter.Serialize(stream, items);
26 stream.Close();
27 }
28
29 public T Deserialize( string sFile)
30 {
31 IFormatter formatter = new BinaryFormatter();
32 Stream stream = new FileStream(HttpContext.Current.Server.MapPath(sFile), FileMode.Open,
33 FileAccess.Read, FileShare.Read);
34 T items = (T)formatter.Deserialize(stream);
35 stream.Close();
36 return items;
37 }
38 }
39
2 using System.Data;
3 using System.Configuration;
4 using System.Web;
5 using System.Web.Security;
6 using System.Web.UI;
7 using System.Web.UI.WebControls;
8 using System.Web.UI.WebControls.WebParts;
9 using System.Web.UI.HtmlControls;
10 using System.Runtime.Serialization;
11 using System.IO;
12 using System.Runtime.Serialization.Formatters.Binary;
13
14 /// <summary>
15 /// Summary description for FileIO
16 /// </summary>
17 public class FileIO < T >
18 {
19 public void Serialize(T items, string sFile)
20 {
21 IFormatter formatter = new BinaryFormatter();
22
23 Stream stream = new FileStream(HttpContext.Current.Server.MapPath(sFile), FileMode.Create,
24 FileAccess.Write, FileShare.None);
25 formatter.Serialize(stream, items);
26 stream.Close();
27 }
28
29 public T Deserialize( string sFile)
30 {
31 IFormatter formatter = new BinaryFormatter();
32 Stream stream = new FileStream(HttpContext.Current.Server.MapPath(sFile), FileMode.Open,
33 FileAccess.Read, FileShare.Read);
34 T items = (T)formatter.Deserialize(stream);
35 stream.Close();
36 return items;
37 }
38 }
39
将数据集序列化为本地文件时,需在本地新建一个BIN文件,即新建一个文本文件,然后把文本文件的后缀名"txt"改为"bin"
DataSet dsList
=
new
DataSet()
// 填充数据集
FileIO < DataSet > file = new FileIO < DataSet > ();
file.Serialize(dsList, " cache/cache.bin " ); // 序列化缓存
Cache[ " mDS " ] = dsList;
// 填充数据集
FileIO < DataSet > file = new FileIO < DataSet > ();
file.Serialize(dsList, " cache/cache.bin " ); // 序列化缓存
Cache[ " mDS " ] = dsList;
读取本地文件
FileIO
<
DataSet
>
file
=
new
FileIO
<
DataSet
>
();
ds = file.Deserialize( " cache/cache.bin " );
ds = file.Deserialize( " cache/cache.bin " );
参考:http://www.cnblogs.com/eicesoft/archive/2007/09/11/889654.html