【问题标题】:Manipulate .html file from code-behind从代码隐藏操作 .html 文件
【发布时间】:2012-09-07 10:46:02
【问题描述】:

我的 asp.net webforms 项目中有一个 html 文件,人们可以在单击按钮时下载该文件。

我想在文件发送给用户之前根据一些数据库值生成一些<select> 列表并附加到 html 的某些部分。这可能使用c#吗?我目前的下载功能:

public void DownloadOfflineAuditSheetEditor(object s, EventArgs e)
{
    Response.AppendHeader("content-disposition", "attachment; filename=thefile.html");
    Response.WriteFile(Server.MapPath("~/thefile.html"), true);
    Response.End();
}

【问题讨论】:

标签: c# asp.net .net html


【解决方案1】:

是的 - 您必须在将“文件”发送给用户之前对其进行操作。

在您的方法DownloadOfflineAuditSheetEditor 中,您可以调用一个新方法来读取当前文件,从数据库中获取内容,然后写入文件或新文件,例如:

public void GenerateRealTimeContent() 
{

   var path = Server.MapPath("~/thefile.html");
   var dbContent = Database.GetContent(); // returns the <select> Options
   string[] lines = System.IO.File.ReadAllLines(path);
   StringBuilder sb = new StringBuilder();

   foreach (var line in lines) 
   {
     if (line == "CONTENT WHERE YOU WANT TO EDIT") 
     {
        SB.AppendLine(dbContent);
     }

     SB.AppendLine(line);
   }

  // code to write to your file

}

然后在你原来的函数中做:

public void DownloadOfflineAuditSheetEditor(object s, EventArgs e)
{
   GenerateRealTimeContent();
   Response.AppendHeader("content-disposition", "attachment; filename=thefile.html");
   Response.WriteFile(Server.MapPath("~/thefile.html"), true);
   Response.End();
}

http://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx - 从文件中读取

http://msdn.microsoft.com/en-us/library/aa287548(v=vs.71).aspx - 写入文件

【讨论】:

  • 同意,我他使用 xhtml 而不是 html 作为文件内容,他可以使用 LinqToXml 在将实时内容流式传输到客户端之前轻松添加实时内容。
  • 谢谢,这正是我需要的帮助
【解决方案2】:

您可以使用 StreamReader 读取文件,对其进行编辑或添加任何内容并将所有内容写入 Resposne。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多