转:C# 序列化+文件系统 实现数据缓存
实现原理:将object类型数据序列化后存入文件中,进行缓存。一般用于缓存从数据库取出的大量数据,因为从硬盘上直接读取比访问数据库的速度快很多。但是适应用于大量数据,因为数据量小时,缓存在内存中会更快。
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
///MyCache 的摘要说明
/// </summary>
public class MyCache
{
private string folderPath = string.Empty;
/// <summary>
/// 缓存时间分钟
/// </summary>
private int expires = 0;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="folderPath">缓存文件夹</param>
/// <param name="expire">缓存时间/分钟</param>
public MyCache(string folderPath, int expire)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
this.folderPath = folderPath;
this.expires = expire;
}
/// <summary>
/// 缓存数据
/// </summary>
/// <param name="filename">文件名</param>
/// <param name="datas">数据</param>
/// <returns></returns>
public bool CacheDatas(string filename, object datas)
{
IFormatter fm = new BinaryFormatter();
try
{
Stream fStream = new FileStream(folderPath + filename, FileMode.Create,FileAccess.Write, FileShare.Write);
fm.Serialize(fStream, datas);
fStream.Flush();
fStream.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 读取缓存数据
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>缓存数据</returns>
public object ReadDatas(string filename)
{
string filePath = folderPath + filename;
IFormatter fm = new BinaryFormatter();
if (File.Exists(filePath))
{
if (DateTime.Now > File.GetCreationTime(filePath).AddMinutes(expires))
{
return null;
}
try
{
Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read,FileShare.Read);
object datas = fm.Deserialize(stream);
return datas;
}
catch
{
return null;
}
}
else
{
return null;
}
}
}
调用示例:
string folderPath = Server.MapPath(".\\Caches\\");
MyCache cache = new MyCache(folderPath,60);
string fileName = HttpUtility.UrlEncode(Request.Url.ToString()) + ".cache"; //文件名 , .cache为自定义文件类型
if (cache.ReadDatas(fileName) == null)
{
SqlDataAdapter ad = new SqlDataAdapter("select * from employee_basic","server=.;database=SZMMY_ERP;uid=sa;pwd=sa;");
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
cache.CacheDatas(fileName, dt);
}
else
{
dt = (DataTable)cache.ReadDatas(fileName);
}