Downloading File using Response Object

B

brian.fairchild

I have a downloader page in my asp.net application that looks at a
session variable to get the path to the file, checks it then downloads
it using the Response object. When the "File Download" dialog comes up,
if the user clicks "Save" and then opens the file, it works great. If
the user clicks save and then opens the document up from their local
computer it always (100%) works fine. However, if they choose "Open"
instead then most of the time (90%) the right application launches on
the users computer, but then fails opening the document. Most of the
office applications report back that the file could not be found, and
shows the path to the file in the Contents of the IE directory
structure. However, Adobe Acrobat just reports that the document could
not be opened.

Here's my code for the downloader:
<code>
string path = Session["filedownloadpath"].ToString();

if(File.Exists(path))
{
FileInfo fi = new FileInfo(path);
Response.Clear();
Response.Buffer = false;
switch(fi.Extension)
{
case ".pdf":
// Response.ContentType = "application/pdf";
break;
default:
// Response.ContentType = "application/octet-stream";
break;
}

string name = Path.GetFileName(path);
Response.ContentType = "application/x-msdownload";
Response.AddHeader("Content-Disposition","attachment;filename= "
+ fi.Name);
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.Flush();
FileStream iStream = new FileStream(path,
System.IO.FileMode.Open,
FileAccess.Read,
FileShare.Read);

byte[] buffer = new byte[10000];
int length = 0;
long datatoread = 0;
datatoread = iStream.Length;
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
{
datatoread = -1;
}
}
iStream.Close();
//Response.WriteFile(path);
Response.End();

}
else
{
throw new Exception("File Not Found");
}
</code>

I have tried this in Firefox and it works fine. Any suggestions? Anyone
else run into this lately?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top