File download - does not exist in temporary files
Hi
I'm streaming a file down to the browser as it is stored outside the website path using the following method:
Code:
FileInfo file = new FileInfo(ConfigurationSettings.AppSettings["DocumentLibraryPath"] + lblDocumentUrl.Text);
Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
try {
iStream = new FileStream(file.FullName,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
dataToRead = iStream.Length;
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", iStream.Length.ToString());
Response.ContentType = "application/octet-stream";
while (dataToRead > 0) {
if (Response.IsClientConnected) {
length = iStream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer= new Byte[10000];
dataToRead = dataToRead - length;
} else {
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
Response.End();
}
catch (Exception ex) {
lblDownloadError.Text = String.Format("<p>Download error: {0}</p>", ex.Message.Replace(ConfigurationSettings.AppSettings["DocumentLibraryPath"], ""));
}
finally {
if (iStream != null) {
iStream.Close();
}
}
As I use the content-type application/octet-stream it forces the Open, Save or Cancel dialog to be shown.
This works fine when you choose to save. However sometimes if you choose to open the file the application that tries to open it (tried Acrobat, Word and Powerpoint) says the file cannot be found. It's like the file is deleted from the temporary files before the application can launch it.
Anyone experienced this - any suggestions?
DJ