2012-09-14 60 views
0

我在我的asp.net webforms項目中有一個html文件,人們可以在單擊按鈕時下載該文件。從代碼隱藏操作.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(); 
} 
+2

看看[HtmlAgilityPack](http://stackoverflow.com/questions/2422762/html-agility-pack) – StuartLC

+0

@nonnb Thans提示,看起來不錯! – Johan

回答

2

是的 - 您必須在發送給用戶之前操​​作「文件」。

在你的方法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讀 - 寫一個文件

+0

同意,我使用xhtml代替文件內容的html,他可以使用LinqToXml輕鬆地將實時內容添加到客戶端之前。 – Kevin

+0

謝謝,這只是我需要的幫助 – Johan

0

您可以使用StreamReader讀取文件,編輯它或添加任何內容並將所有內容寫入Resposne中。