Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Im trying to save a file from sql server database table fields are(FileID, FileName, ContentType, FileData) and cant seem to use FileStream without specifying a local path.

this is my method to retrieve the file, but it requires a local path not IIS...

private void Download(DataTable dt)
    {
        Byte[] bytes = (Byte[])dt.Rows[0]["FileData"];
        string fileName = dt.Rows[0]["FileName"].ToString();
        
        FileStream fs =
            new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

        BinaryWriter bw = new BinaryWriter(fs);       
        
        bw.Write(bytes, 0, bytes.Length);
        bw.Close();
        bw.Flush();
        
        fs.Close();

        Response.ClearContent();
        Response.Clear();
        Response.ContentType = dt.Rows[0]["ContentType"].ToString();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.TransmitFile(fileName);
        Response.Write(fs);

        Response.Flush();
        Response.End();


Any help would be greatly appreciated.Thanks in advance!
Posted

1 solution

C#
Byte[] bytes = (Byte[])dt.Rows[0]["FileData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
                + dt.Rows[0]["FileName"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
 
Share this answer
 
Comments
nebiam 2-Jun-14 3:57am    
I have tried this, and no popup "save as" dialogue appears. It actually does nothing. Stepping through it returns the content type and filename ect..
nebiam 3-Jun-14 21:07pm    
This infact works perfectly! I had the control (repeater) nested in an update panel.. which is why it would not work to begin with. In fact both blocks of code posted will work. To get the code working in an update panel, i added a trigger for the control to the update panel.

<Triggers>
<asp:PostBackTrigger ControlID="ControlID" />
</Triggers>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900