2013-07-29 68 views
1

我有這個功能生成一個XML文件..問題是,當我下載生成的文件,我有我的XML格式正確,但在本月底也將HTML頁面的源代碼,我已經點擊了按鈕來生成這個。問題是什麼?這裏的源代碼:XmlTextWriter的C#打印也頁面的HTML源代碼

protected void lnkEsporta_Click(object sender, EventArgs e) 
    { 
     List<Eventi> lista_eventi = //load list 

     string filename = "~/data/eventi.xml"; 



     XmlTextWriter tw = new XmlTextWriter(Server.MapPath(filename), Encoding.GetEncoding("ISO-8859-1")); 
     tw.Flush(); 
     tw.Formatting = Formatting.Indented; 

     tw.WriteStartDocument(); 
     tw.WriteStartElement("wrapper"); 
     tw.WriteElementString("project", GetDao().Get<Progetti, Int32>(lista_eventi[0].idprogetto).nome); 

     tw.WriteStartElement("events"); 

     foreach (Eventi evento in lista_eventi) 
     { 
      tw.WriteStartElement("event"); 

      tw.WriteElementString("idEv", evento.idev.ToString()); 
      tw.WriteElementString("data", evento.DataInizio.ToString()); 
      tw.WriteElementString("sede", evento.sede.ToString()); 
      tw.WriteElementString("location", evento.location.ToString()); 
      tw.WriteElementString("video", evento.video ? "True" : "False"); 
      tw.WriteElementString("tutors", evento.tutors.ToString()); 
      tw.WriteElementString("technicians", evento.technicians.ToString()); 

      tw.WriteStartElement("aule"); 

      List<Aule> lista_aule = //load list 
      foreach (Aule aula in lista_aule) 
      { 
       tw.WriteElementString("aula", aula.descrizione.ToString(), aula.idaula.ToString()); 
      } 

      tw.WriteEndElement(); 

      tw.WriteEndElement(); //end of source event 
     } 

     tw.WriteEndElement();//end of source events 
     tw.WriteEndElement();//end of source wrapper 

     tw.WriteEndDocument();//end of source tag 

     tw.Close(); 


     Response.ClearContent(); 
     //Response.End(); 
     Response.Clear(); 

     Response.StatusCode = 200; 

     Response.AddHeader("content-disposition", "attachment; filename=" + filename); 
     Response.AddHeader("Content-Transfer-Encoding", "binary"); 
     //Response.AddHeader("Content-Length", _Buffer.Length.ToString()); 

     Response.ContentType = "application-download"; 


     Response.TransmitFile(Server.MapPath(filename)); 




    } 

我已經在開始我的xml,之後它開始與頁面源代碼...我能做什麼?非常感謝您的幫助!

+0

有一點需要注意:'XmlWriter'是建立在內存中的XML文檔,然後寫出來比較痛苦。除非你真的期待大文件,否則我只會使用LINQ to XML。 –

回答

0

我建議你缺少Response.End()

又見Filename and mime problems - ASP.NET Download file (C#)

Response.ContentType = "application/xml"; 
    Response.AddHeader("Content-Disposition", String.Format("inline; filename={0}.xml", Path.GetFileName(Path))); 

    Response.WriteFile(path); // 
    Response.Flush(); 
    // Response.Close(); // end should do this anyway so optional 
    Response.End(); // end forces the server to send the request immediately. Failing to 
+0

我注意到代碼中StatusCode被設置爲200。這可能也是一個問題,因爲可能導致輸出被解釋爲HTML頁面而不是文件流。 – Max

+0

解決了!謝謝! – Stefano