ASP.NET实现新闻页面的分页功能
//生成静态网页
string path = Server.MapPath("~/news/" + folder + "/");
string file_template_name = Server.MapPath("~/news/template.htm"); //新闻模版文件
string file_template_content = "";
StreamReader sr_reader = new StreamReader(file_template_name, Encoding.GetEncoding("gb2312"));
file_template_content = sr_reader.ReadToEnd();
sr_reader.Close();
string[] subContent = FileSplit(content);
string file_content = "";
int pageNum = 0;
while (pageNum pageNum++;
for (int index = 0; index {
file_content = file_template_content;
file_content = file_content.Replace("$category", list_department.SelectedItem.Text); //新闻类别
file_content = file_content.Replace("$title", title); //新闻标题
file_content = file_content.Replace("", "来源:" + author); //作者
file_content = file_content.Replace("$time", time); //添加时间
file_content = file_content.Replace("$content", subContent[index]); //新闻正文
string pageLink = "";
int firstPage = 0;
//生成页码
if (index > 2) firstPage = index - 2;
for (int i1 = firstPage; i1 {
if (i1 == index)
pageLink = pageLink + "[" + (index + 1) + "]" + " ";
else pageLink = pageLink + "[" + (i1 + 1) + "] ";
if (index pageLink = pageLink + "" + "下一页" + " ";
if (index > 0)
pageLink = "" + "上一页" + " " + pageLink;
file_content = file_content.Replace("", pageLink);
if (index == pageNum - 1&&attachment_filename != null && attachment_filename != String.Empty)
string[] attachment = attachment_filename.Split(new char[] { "|" });
string attachmenthtml = "" + attachment[0] + "";
for (int j = 1; j attachmenthtml = attachmenthtml + "
" + attachment[j] + "";
file_content = file_content.Replace("$attachment", attachmenthtml);
StreamWriter sw = new StreamWriter(path + htmlfilename + index + ".htm", false, Encoding.GetEncoding("gb2312"));
sw.Write(file_content);
sw.Flush();
sw.Close();
HyperLink1.Text = "预览: " + title;
HyperLink1.NavigateUrl = "/news/" + folder + "/" + htmlfilename + "0" + ".htm";
HyperLink1.Visible = true;
txt_time.Text = DateTime.Now.ToString("yyyy-MM-dd");
txt_title.Text = "";
txt_author.Text = "";
FreeTextBox1.Text = "";
catch (Exception e)
//将正文分成多个页面
protected string[] FileSplit(string fileContent)
int fileIndex = 0;
string[] splitedFile = new string[10];
while (fileContent.Length > 1500 && fileIndex {
if (fileContent.IndexOf("
", 1500) splitedFile[fileIndex] = fileContent.Substring(0, fileContent.IndexOf("
", 1500));
fileContent = fileContent.Remove(0, splitedFile[fileIndex].Length);
fileIndex++;
splitedFile[fileIndex] = fileContent; //超过9页,剩下部分全放第十页
return splitedFile;
}来源华军资讯编辑整理)
(责任编辑:Newshoo)