TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

HOWTO: Send a File to the Browser Prompting "Save As" with ASP.NET

Basically this sample code shows you how to stream XML data down to the browser from a DataSet and prompt the user to save the file instead of having the XML render in the browser.

//Make a test DataSet

DataSet ds = new DataSet();

ds.Tables.Add("TestTable");

DataTable t = ds.Tables["TestTable"];

t.Columns.Add("ID");

t.Columns.Add("TestGUID");

t.Columns.Add("DateTime");

for(int i = 0; i < 10; i++)

    t.Rows.Add(new object[] {i, Guid.NewGuid().ToString(), DateTime.Now.ToLongTimeString()});

 

StreamWriter writer = null;

try

{

    writer = new System.IO.StreamWriter(Page.MapPath("test.xml"), false, Encoding.ASCII);

    writer.Write(ds.GetXml());

}

finally

{

    writer.Close();

}

 

Response.Clear();

FileInfo fileInfo = new FileInfo(Page.MapPath("test.xml"));

Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);

Response.AddHeader("Content-Length", fileInfo.Length.ToString());

Response.ContentType = "application/octet-stream";

Response.WriteFile(fileInfo.FullName);

Response.End();


Digg!

posted on Tuesday, July 06, 2004 11:10 AM

Feedback

# Thanks 1/26/2005 4:46 PM Dave

Worked perfectly the first time with not problems. Thanks!