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();
}