asp.net 将数据静态化
protected void Page_Load(object sender, EventArgs e)
{
LoadHtml();
}
数据从何而来??
#region 内容的读取 解释:如果已经静态化过了,就从 生成的静态文件获取数据,如果是第一次,就从数据源获取文件, 然后将其,第一次静态化
/// <summary>
/// 从静态文件获取
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
private string GetHtmlFromStaicFile(string filePath)
{
string content = Tool.FileHelper.ReadFile(filePath); --注意,tool是我们自己定义的公共库,ReadFile只是读取文件的方法
return content;
}
/// <summary>
/// 从数据库中加载
/// </summary>
/// <param name="diaryId"></param>
/// <returns></returns>
private string GetHtmlFromDB(long diaryId, out int power)
{
var data = Role.DiaryBLL.GetDiaryById(diaryId);
Page page = new Page();
var control = page.LoadControl("~/UserControl/CtrDetailTemplate.ascx") as CtrDetailTemplate;
page.Controls.Add(control);
control.Dary = data;
StringWriter strWriter = new StringWriter();
Server.Execute(page, strWriter, false);
string str = strWriter.ToString();
strWriter.Close();
diaryTitle = data.Title; //下面这些是你需要的数据
userName = data.PublisherName;
metaDescript = Tool.WebTool.CutString(data.Content, 200);
return str;
}
#endregion
//,文件是如何写入的??
#region
/// <summary>
/// 写入静态文件
/// </summary>
/// <param name="fileContent"></param>
/// <param name="fileRootPath"></param>
/// <param name="powerID"></param>
/// <param name="diaryId"></param>
private void writeFileToStaicFile(string fileContent, string fileRootPath, int powerID, long diaryId)
{
if (!Directory.Exists(fileRootPath))
{
Directory.CreateDirectory(fileRootPath);
}
string filePowerPath = fileRootPath + "\\" + powerID + "\\";
if (!Directory.Exists(filePowerPath))
{
Directory.CreateDirectory(filePowerPath);
}
string filePath = filePowerPath + "\\" + diaryId.ToString() + ".html";
//写入文件
Tool.FileHelper.WriteFile(filePath, fileContent); //将内容写到指定路径
}
#endregion
#region
// 加载数据的方法
/// <summary>
/// 加载文章HTML
/// </summary>
/// <param name="diaryId"></param>
/// <param name="UId"></param>
/// <returns></returns>
private string LoadHtml(long diaryId, Guid UId)
{
bool isFindHtml = false;
string filePath = "";
string rootpath = HttpContext.Current.Server.MapPath("/journal/DiaryDetailHTML/" + uId + "/");//路径
if (!Directory.Exists(rootpath))
{
Directory.CreateDirectory(rootpath);
isFindHtml = false;
}
else
{
string[] dirAllDir = Directory.GetDirectories(rootpath);
for (int j = 0; j < dirAllDir.Length; j++)
{
filePath = rootpath + dirAllDir[j] + "\\" + diaryId;
if (File.Exists(filePath))
{
Power = Convert.ToInt32(dirAllDir[j]);
isFindHtml = true;
break;
}
}
}
//处理加载或者保存数据
if (isFindHtml)
{
//如果是已经静态化过的数据
return GetHtmlFromStaicFile(filePath);
}
else
{
//第一次加载数据
string diaryContent = GetHtmlFromDB(lDiaryId, out Power);
//存储硬盘
writeFileToStaicFile(diaryContent, rootpath, Power, diaryId);
return diaryContent;
}
}
#endregion