Repeater nesnesinin ItemCommand event’inde CommanArgument olarak resmin saklandığı url adresini tuttuk. Aşağıdaki kodla herhangi bir url adresindeki resmi bilgisayarınıza indirebilirsiniz.

protected void RepeaterSlider_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if(e.CommandName== "Indir")
            {
                string strRealname = Path.GetFileName(e.CommandArgument.ToString());
                Stream stream = null;
                int bytesToRead = 10000;
                byte[] buffer = new Byte[bytesToRead];
                try
                {
                    HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(e.CommandArgument.ToString());
                    HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
                    if (fileReq.ContentLength > 0)
                        fileResp.ContentLength = fileReq.ContentLength;
                    stream = fileResp.GetResponseStream();
                    var resp = HttpContext.Current.Response;
                    resp.ContentType = "application/octet-stream";
                    resp.AddHeader("Content-Disposition", "attachment; filename=\"" + strRealname + "\"");
                    resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
                    int length;
                    do
                    {
                        if (resp.IsClientConnected)
                        {
                            length = stream.Read(buffer, 0, bytesToRead);
                            resp.OutputStream.Write(buffer, 0, length);
                            resp.Flush();
                            buffer = new Byte[bytesToRead];
                        }
                        else
                        {
                            length = -1;
                        }
                    } while (length > 0); 
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }

            }
Written by Sümeyra Akbıyık
hakkımdaki her şeyi bu blogda bulabilirsin. Haydi sende bir göz gezdirmeye ne dersin?

Leave a Comment