Downloading File using Response Object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • brian.fairchild@gmail.com

    Downloading File using Response Object

    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["filedownloadpa th"].ToString();

    if(File.Exists( path))
    {
    FileInfo fi = new FileInfo(path);
    Response.Clear( );
    Response.Buffer = false;
    switch(fi.Exten sion)
    {
    case ".pdf":
    // Response.Conten tType = "applicatio n/pdf";
    break;
    default:
    // Response.Conten tType = "applicatio n/octet-stream";
    break;
    }

    string name = Path.GetFileNam e(path);
    Response.Conten tType = "applicatio n/x-msdownload";
    Response.AddHea der("Content-Disposition","a ttachment;filen ame= "
    + fi.Name);
    Response.AddHea der("Content-Length", fi.Length.ToStr ing());
    Response.Flush( );
    FileStream iStream = new FileStream(path ,
    System.IO.FileM ode.Open,
    FileAccess.Read ,
    FileShare.Read) ;

    byte[] buffer = new byte[10000];
    int length = 0;
    long datatoread = 0;
    datatoread = iStream.Length;
    while(datatorea d>0)
    {
    if(Response.IsC lientConnected)
    {
    length = iStream.Read(bu ffer, 0, 10000);
    Response.Output Stream.Write(bu ffer, 0, length);
    Response.Flush( );
    buffer = new byte[10000];
    datatoread = datatoread - length;
    }
    else
    {
    datatoread = -1;
    }
    }
    iStream.Close() ;
    //Response.WriteF ile(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?

Working...