ASP.Net的緩存技術大大地提高了效率,本人將代碼的簡單的實現代碼貼出:
一、在頁面中顯示時,讀緩存數據,加載XML數據
public void LoadData()
{
DataView Source = (DataView)Cache["MyData"];
if(Source == null)
{
DataSet ds = new DataSet();
FileStream fs = new FileStream(Server.MapPath("LoginMsg.xml"), FileMode.Open,FileAccess.Read);
StreamReader reader = new StreamReader(fs);
ds.ReadXml(reader);
fs.Close();
Source = new DataView(ds.Tables[0]);
Cache.Insert("MyData", Source, new CacheDependency(Server.MapPath("LoginMsg.xml")));
ErrorMsg.Text = "從文件中讀取的數據";
}
else
{
ErrorMsg.Text = "從緩存中讀取的數據";
}
MyDataGrid.DataSource = Source;
MyDataGrid.DataBind();
}
二、用XML存儲交互數據,將數據放置到緩存中
private void LoginMsg_Click(object sender, System.EventArgs e)
{
if(!Page.IsValid)
{
ErrorMsg.Text = "必需輸入登錄信息";
return;
}
DataSet ds = new DataSet();
FileStream fs = new FileStream(Server.MapPath("LoginMsg.xml"),FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs);
ds.ReadXml(reader);
fs.Close();
DataTable dt = ds.Tables[0];
DataRow newrow = dt.NewRow();
newrow["custom_email"] = CustomEamil.Text;
newrow["custom_pass"] = CustomPass.Text;
newrow["login_time"] = DateTime.Now.ToString();
fs = new FileStream(Server.MapPath("LoginMsg.xml"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
TextWriter writer = new StreamWriter(fs);
writer = TextWriter.Synchronized(writer);
ds.Tables[0].Rows.Add(newrow);
ds.WriteXml(writer);
writer.Close();
Cache.Remove("MyData");
LoadData();
}