继续研究静态页面(日期文件夹和数据库)
上文中asp.net下实现静态页面(html)主要实现了静态页面的生产过程,实际过程中我们需要根据不同的年月建立不同的文件夹,以存放不同的新闻。同时,把添加的新闻存放到数据库下面。
接着Conn.cs类文件,改WriteFile方法返回类型为string, 在WriteFile方法的前面添加以下代码:
string path = HttpContext.Current.Server.MapPath("/myservers/news");//取得新闻当前文件夹
   DateTime year = DateTime.Now;
   string years = Convert.ToString(year.Year);//当前年
   string month = Convert.ToString(year.Month);//当前月
   string CurrentPath = path + "/" + years; //设置当前年目录
          if(Directory.Exists(CurrentPath)==false) //若该目录不存在,创建该目录
         Directory.CreateDirectory(CurrentPath);
   string CurrentMonthPath = CurrentPath + "/" + month;//设置当前月目录
              if(Directory.Exists(CurrentMonthPath)==false) //若该目录不存在,创建该目录
         Directory.CreateDirectory(CurrentMonthPath);
以上主要是根据当前日期,判断文件夹是否存在,不存在就创建文件夹。
string htmlfilename=CurrentMonthPath +"/" + datepath ;//文件存在路径和名称
sw = new StreamWriter(htmlfilename,false,code);
最后将创建的HTML文件的路径和名称返回:
string paths = "news/" + years + "/" + month + "/" + datepath;
 return paths;
添加新闻到数据库:
protected void AddData(string mypath)
  {
   string conn = "server=localhost;uid=sa;pwd=963100;database=mis";
   string sqlstr = "insert into news (name,title,content,author,path) values ('"+this.Title.Text.ToString()+"','"+this.Title.Text.ToString()+"','"+this.Content.Value+"','"+this.Author.Text.ToString()+"','"+mypath+"')";
   SqlConnection myconn = new SqlConnection(conn);
   myconn.Open();
   SqlCommand mycommand = new SqlCommand(sqlstr,myconn);
   int i = mycommand.ExecuteNonQuery();
  }
添加新闻时调用AddData()
string htmlpath = Hover.WriteFile(this.Title.Text.ToString(),Server.HtmlDecode(this.Content.Value).ToString(),this.Author.Text.ToString());
this.AddData(htmlpath);
最后在aspx文件上显示新闻:
protected void BindData()
  {
   string conn = "server=localhost;uid=sa;pwd=963100;database=mis";
   string sqlstr = "select * from news";
   SqlConnection myconn = new SqlConnection(conn);
   myconn.Open();
   SqlDataAdapter dr = new SqlDataAdapter(sqlstr,myconn);
   DataSet ds = new DataSet();
   dr.Fill(ds);
   this.dg_News.DataSource = ds.Tables[0].DefaultView;
   this.dg_News.DataBind();
  }
                    
                
                
            
        
浙公网安备 33010602011771号