0

I have an XML file written in C# using StreamWriter with this code:

String filename = Session.SessionID + ".xml";
String filepath = "h:\\root\\home\\mchinni-001\\www\\site1\\OUTFolder\\" + filename;
StreamWriter sw = new StreamWriter(filepath, false);

I fill strOut with the formatted contents of my XML file then I do:

sw.WriteLine(strOut);
sw.Close();

When I check the file on the web server, it looks perfect (for my purposes).

I then try to download it with:

Response.ContentType = "application/xml";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
Response.TransmitFile(filepath);
Response.End();

That download has worked sometimes, but most of the time, I get a "missing file" notice in my downloads area & no file at all gets downloaded (not even a 0-length file).

How do I get this file downloaded?

I've read a bit about the "proper" way to write an XML file in C# but my code already generates a (for my purposes) properly formatted XML file & I'd rather not have to do a major/massive rewrite if I can avoid it.

BTW, I've also tried:

Response.ContentType = "text/xml";

and

Response.ContentType = "text/plain";

but neither of them ever worked.

1
  • 1
    "That download has worked sometimes, but most of the time" - is it for the same file or certain filenames? have the file closed properly and no other application locked it (e.g. anti virus)? also, why didn't you declare the Content-Length header? it can help browser handling download..
    – Bagus Tesa
    Commented Jan 11 at 6:14

2 Answers 2

1

Make sure to flush the StreamWriter before closing it. This ensures that all the data is written to the file before attempting to transmit it.

Include Response.BufferOutput = true;, it allows the server to buffer the output before sending it to the client, which can help in the context of file downloads.

String filename = Session.SessionID + ".xml";
String filepath = "h:\\root\\home\\mchinni-001\\www\\site1\\OUTFolder\\" + filename;
StreamWriter sw = new StreamWriter(filepath, false);

sw.WriteLine(strOut);
sw.Flush();
sw.Close();

Response.BufferOutput = true;
if (File.Exists(filepath))
{
    Response.ContentType = "application/xml";
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

    Response.TransmitFile(filepath);
    Response.End();
}
else
{
    Response.Write("File not found.");
}
0

I added a "sw.Flush()", a "Response.BufferOutput = true" & a Content-Length header and the download now reliably works! YAY! 😁

Thank you to all who responded!!!

Not the answer you're looking for? Browse other questions tagged or ask your own question.