2009/04/08

The "Save As" function on the web form

Here is how I implement the "Save As" function: (let users download files from server)
private void SaveAs(string contents, string fileName)
{
  try
  {
    //setup the HTTP Header and push the contents to clients
    Response.ClearHeaders();
    Response.Clear();
    Response.Expires = 0;
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.AddHeader("Content-Length", contents.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.Write(contents);
    Response.End();
  }
  catch (Exception ex)
  {
    //your error handling here
  }
}

How to call this method? This is one of the ways:
FileInfo oTargetFile = new FileInfo(Server.MapPath("Errorlog.xml"));
if (oTargetFile.Exists)
{
  using (StreamReader oStreamReader = new StreamReader(Server.MapPath("Errorlog.xml")))
  {
    SaveAs(oStreamReader.ReadToEnd(), "Errorlog.xml");
  }
}
oTargetFile = null;

No comments:

Post a Comment