TransmitFile() private méthode

private TransmitFile ( System.Web.Hosting.VirtualFile vf ) : void
vf System.Web.Hosting.VirtualFile
Résultat void
        public ActionResult ExportCSV(string emailList)
        {
            string FilePath = Server.MapPath("/App_Data/");
            string FileName = "EmailList.csv";

            System.IO.File.WriteAllText(FilePath + FileName, emailList);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/csv";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath + FileName);
            response.Flush();
            System.IO.File.Delete(FilePath + FileName); // Deletes the file on server

            response.End();
            List <string> listOfEmails = emailList.Split(',').ToList();

            foreach (var emailName in listOfEmails)
            {
                //Takes each email in list and searches for it on the JPStudents table and finds the associated ApplicationUserID.
                //Then calls the UpdateLatestContact method on each ApplicationUserID.
                var userId = db.JPStudents.Where(x => x.JPEmail == emailName).First().ApplicationUserId.ToString();
                UpdateLatestContact(userId);
            }
            return(RedirectToAction("Index"));
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //Save a trial user to the database
                string version = ConfigurationManager.AppSettings["Version"];

                if (string.IsNullOrEmpty(version))
                {
                    //throw error and return
                    return;
                }

                string trialDownloadPath = "~\\Releases\\" + version + "\\Utility\\Downloadables\\Trial\\SimpleSqliteUtility.zip";

                //Transmit the files
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.ClearContent();
                response.Clear();
                response.ContentType = "text/plain";
                response.AddHeader("Content-Disposition", "attachment; filename=SimpleSqliteUtility.zip;");
                response.TransmitFile(trialDownloadPath);
                response.Flush();
                response.End();
            }
            catch (Exception ex)
            {
                //Report error in an email
            }
        }
Exemple #3
0
        private void Descargar(ArrayList arrText)
        {
            string fic = Server.MapPath(@"TextFiles/polizavta.txt");

            StreamWriter sw = new StreamWriter(fic, false, Encoding.UTF8);

            if (arrText.Count > 0)
            {
                for (int i = 0; i < arrText.Count; i++)
                {
                    sw.WriteLine(arrText[i].ToString());
                }
            }
            sw.Close();

            //String FileName = "BulkAdd_Instructions.txt";
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=polizavta.txt;");
            response.TransmitFile(fic);
            response.Flush();
            response.End();
        }
Exemple #4
0
        public ActionResult Download(ModelFile file)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    GenerateFile(file.MaxValue, file.FileAmount);

                    var fileName = "GenerateFile.txt";

                    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                    response.ClearContent();
                    response.Clear();
                    response.ContentType = "text/plain";
                    response.AddHeader("Content-Disposition",
                                       "attachment; filename=" + fileName + ";");
                    response.TransmitFile(Server.MapPath("~/GenerateFile.txt"));
                    response.Flush();
                    response.End();
                }
            }
            catch
            {
                return(View("Download"));
            }

            return(View());

            //return null;
        }
 protected void btnDownloadPKCS12Certificate_Click(object sender, EventArgs e)
 {
     try
     {
         //***TESTIRANJE***Session["Preuzimanje-softverskog-sertifikata-pkcs12"] = @"\\ca-sajt.ca.posta.rs\c$\inetpub\wwwroot\Posta\Dokumentacija\P12_FOLDER\Sertifikat-PKCS12-4e624421b7dcb6dbdf-05112018.p12";
         //String FileName = "Sertifikat-PKCS12-338151188815333c-20180605.p12";
         string FileName = @"attachment; filename=""" + Path.GetFileName(Session["Preuzimanje-softverskog-sertifikata-pkcs12"].ToString()) + "";
         //String FilePath = @"C:\inetpub\wwwroot\Posta\Dokumentacija\P12_FOLDER\Sertifikat-PKCS12-338151188815333c-20180605.p12";
         string FilePath = Utils.ConvertToLocalPath(Session["Preuzimanje-softverskog-sertifikata-pkcs12"].ToString());
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.ClearContent();
         response.Clear();
         response.Buffer      = true;
         response.ContentType = "text/plain";
         response.AddHeader("Content-Disposition", FileName); //forse save as dialog in Mozzila an Explorer but no in Chrome
         response.TransmitFile(FilePath);
         response.Flush();
     }
     catch (Exception ex)
     {
         log.Error("Error while saving .p12 file. " + ex.Message);
         ScriptManager.RegisterStartupScript(this, GetType(), "erroralertSendSOAP", "erroralertSendSOAP();", true);
     }
     finally
     {
         HttpContext.Current.Response.End();
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            String FileName = null;

            switch ((string)Session["filetype"])
            {
            case ".txt":
                FileName = "CompressedText.cmx";
                break;

            case ".JPG":
            case ".jpg":
                FileName = "CompressedImage.cmi";
                break;

            case ".cmi":
                FileName = "ExtractedImage.jpg";
                break;

            case ".cmx":
                FileName = "ExtractedText.txt";
                break;
            }

            string fn = Server.MapPath("resources/" + FileName);

            System.Web.HttpResponse responses = System.Web.HttpContext.Current.Response;
            responses.ClearContent();
            responses.Clear();
            responses.ContentType = "text/plain";
            responses.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            responses.TransmitFile(fn);
            responses.Flush();
            responses.End();
        }
        protected void btnSaoLuuDuLieu_Click(object sender, EventArgs e)
        {
            dtSetting dt      = new dtSetting();
            DataTable db      = dt.LayTenDatabase();
            DataRow   dr      = db.Rows[0];
            string    Name    = dr["DatabaseName"].ToString();
            string    CD      = Server.MapPath("~/Uploads/");
            string    TenFile = DateTime.Now.ToString("ddMMyyyy") + "_" + Name + ".Bak";

            data = new dtDuLieu();
            //FileInfo newFile = new FileInfo(Server.MapPath("~/Uploads/" + TenFile));
            //newFile.Delete();
            string[] Files = Directory.GetFiles(Server.MapPath("~/Uploads/"));

            foreach (string file in Files)
            {
                File.Delete(file);
            }
            data.SaoLuuCSDL(CD, Name);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + TenFile + ";");
            response.TransmitFile(Server.MapPath("~/Uploads/" + TenFile));
            response.Flush();
            response.End();
        }
        //protected void btnCancel_Click(object sender, EventArgs e)
        //{
        //    ChangePageMode(Helper.PageMode.New);
        //    ClearPageData();
        //    EditBox.Visible = false;
        //}

        protected void gvYearEnd_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "EditRow")
                {
                    ClearPageData();
                    GridViewRow selectedRow = gvYearEnd.Rows[Convert.ToInt32(e.CommandArgument)];
                    selectedRow.Style["background-color"] = "skyblue";

                    int     yearendid  = Convert.ToInt32(gvYearEnd.DataKeys[selectedRow.RowIndex]["YearEndID"]);
                    YearEnd objYearEnd = ((List <YearEnd>)Session["YearEndData"]).Where(x => x.YearEndID == yearendid).FirstOrDefault();

                    Session["SelectedYearEnd"] = objYearEnd;

                    ddlBudgetType.SelectedIndex = -1;
                    ddlBudgetType.Items.FindByText(objYearEnd.BudgetType.ToString()).Selected = true;
                    ddlBudgetYear.SelectedIndex = -1;
                    ddlBudgetYear.Items.FindByValue(objYearEnd.BudgetYear.ToString()).Selected = true;
                    ddlStatus.SelectedIndex = -1;
                    ddlStatus.Items.FindByValue(objYearEnd.Status).Selected = true;
                    ddlStatus.Enabled = (objYearEnd.Status == "A");

                    ChangePageMode(Helper.PageMode.Edit);
                    EditForm.Visible = true;
                }
                else if (e.CommandName == "Download")
                {
                    GridViewRow selectedRow = gvYearEnd.Rows[Convert.ToInt32(e.CommandArgument)];
                    int         yearendid   = Convert.ToInt32(gvYearEnd.DataKeys[selectedRow.RowIndex]["YearEndID"]);
                    YearEnd     objYearEnd  = ((List <YearEnd>)Session["YearEndData"]).Where(x => x.YearEndID == yearendid).FirstOrDefault();

                    string FolderPath = WebConfigurationManager.AppSettings["ArchiveFolderPath"];
                    string FileName   = objYearEnd.BudgetYear + "_" + objYearEnd.BudgetType + ".xls";

                    if (File.Exists(FolderPath + FileName))
                    {
                        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                        response.ClearContent();
                        response.Clear();
                        response.ContentType = "application/vnd.ms-excel";
                        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
                        response.TransmitFile(FolderPath + FileName);
                        response.Flush();
                        response.End();
                    }
                    else
                    {
                        ((SiteMaster)this.Master).ShowMessage("Failure", "File not found : " + FolderPath + FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                ((SiteMaster)this.Master).ShowMessage("Error", "An error occurred", ex, true);
            }
        }
Exemple #9
0
 /// <summary>
 /// Handles the Load event of the Page control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 protected void Page_Load(object sender, EventArgs e)
 {
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.AddHeader("content-disposition", string.Format("attachment; filename={0}", System.IO.Path.GetFileName(FileName)));
     response.ContentType = "application/octet-stream";
     response.TransmitFile(FileName);
     response.Flush();
     response.End();
 }
 protected void btnDownloadFormat_Click(object sender, EventArgs e)
 {
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.ClearContent();
     response.Clear();
     response.ContentType = "application/excel";
     response.AddHeader("Content-Disposition", "attachment; filename=ImportFormatColumn.xlsx");
     response.TransmitFile(Server.MapPath("/Upload/ImportFormatColumn.xlsx"));
     response.Flush();
     response.End();
 }
 protected void TransmitFile()
 {
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.ClearContent();
     response.Clear();
     response.ContentType = "text/plain";
     response.AddHeader("Content-Disposition", "attachment; filename=" + _fileName + ";");
     response.TransmitFile(_filePath);
     response.Flush();
     response.End();
 }
Exemple #12
0
 //modal ingreso pedidos
 protected void LinkPlantilla_Click(object sender, EventArgs e)
 {
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.ClearContent();
     response.Clear();
     response.ContentType = "text/plain";
     response.AddHeader("Content-Disposition", "attachment; filename=Plantilla.xls");
     response.TransmitFile(Server.MapPath("~/Cliente/Diccionario/Plantillas/Plantilla-DetalledePedido.xls"));
     response.Flush();
     response.End();
 }
 protected void pdf_Click(object sender, ImageClickEventArgs e)
 {
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.ClearContent();
     response.Clear();
     response.ContentType = "text/plain";
     response.AddHeader("Content-Disposition",
                        "attachment; filename=Invoice " + txtNInvoice.Text + ".pdf;");
     response.TransmitFile(Server.MapPath("" + Session["Link"] + ""));
     response.Flush();
     response.End();
 }
Exemple #14
0
 public void ProcessRequest(HttpContext context)
 {
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.ClearContent();
     response.Clear();
     response.ContentType = "Application/msword";
     response.AddHeader("Content-Disposition",
                        "attachment; filename=" + context.Request.QueryString["FileName"] + ";");
     response.TransmitFile(context.Server.MapPath("~/WorkGuides/rtfs/" + context.Request.QueryString["FileName"]));
     response.Flush();
     response.End();
 }
        protected void btnTai_Click(object sender, EventArgs e)
        {
            string filePath = TrangChu.Format(ten);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + filePath + ";");
            response.TransmitFile(Server.MapPath("~/Files/" + filePath));
            response.Flush();
            response.End();
        }
        protected void DownloadFilesBtn_Click(object sender, EventArgs e)
        {
            string FilePath = Request.PhysicalApplicationPath + @"\Downloads";
            string FileName = "AwardScript.txt";

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath + "\\" + FileName);
            response.Flush();
            response.End();
        }
        protected void gvnotacreditos_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int           num  = Convert.ToInt32(e.CommandArgument);
            SqlConnection Conn = new SqlConnection();

            Conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["GESTION.Properties.Settings.CadenadeConeccion"].ToString();
            SqlCommand    cmd = new SqlCommand();
            SqlDataReader dr;

            if (e.CommandName == "Imprimir")
            {
                Session["Selectedvernc"] = e.CommandArgument.ToString();
                string str;
                str = "window.open('ImprimirNC.aspx','Nota de Creditos','width=980px,height=980px,sc rollbars=no,resizable=no')";
                Response.Write("<script languaje=javascript>" + str + "</script>");
            }
            if (e.CommandName == "NotaCD")
            {
                Session["Selectedvernc"] = e.CommandArgument.ToString();
                Conn.Open();
                cmd.Connection  = Conn;
                cmd.CommandText = "SELECT linkpdf,NNC FROM NotaCreditos where id_NC = '" + Session["Selectedvernc"] + "' ";
                dr = cmd.ExecuteReader();
                dr.Read();
                if (dr.HasRows)
                {
                    if (dr["linkpdf"].ToString() == "")
                    {
                        SinNC.Visible = true;
                        NOOK.Visible  = false;
                    }
                    else
                    {
                        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                        response.ClearContent();
                        response.Clear();
                        response.ContentType = "text/plain";
                        response.AddHeader("Content-Disposition", "attachment; filename=Nota de Credito " + dr["NNC"] + ".pdf;");
                        response.TransmitFile(Server.MapPath("" + dr["linkpdf"] + ""));
                        response.Flush();
                        response.End();
                    }
                }
                else
                {
                    SinNC.Visible = true;
                }
                Conn.Close();
            }
        }
Exemple #18
0
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            string filepath = searchresult.filesList[searchresult.currentFileIndex];
            string fileName = Path.GetFileName(filepath);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
            response.TransmitFile(filepath);
            response.Flush();
            response.End();
        }
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            System.Web.HttpRequest  request  = System.Web.HttpContext.Current.Request;
            string fileName = request.QueryString["fileName"];

            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
            response.TransmitFile(System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadDirectory"] + "/" + fileName));
            response.Flush();
            response.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            String fileName       = Request.QueryString["fileName"];
            String excellFilePath = Request.QueryString["excellFilePath"];

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
            response.TransmitFile(excellFilePath.Replace('*', '\\'));
            response.Flush();
            response.End();
        }
Exemple #21
0
        protected void DownloadFile(object sender, EventArgs e)
        {
            String FilePath = (sender as LinkButton).CommandArgument; //Replace this

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "application/octet-stream";
            //response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FilePath) + ";");
            response.TransmitFile(FilePath);
            response.Flush();
            response.End();
        }
Exemple #22
0
    protected void btnSample_Click(object sender, EventArgs e)
    {
        //Response.Redirect(Server.MapPath("FileTemplates/Template.xlsx"));

        string FileName = "Template.xlsx"; // Its a file name displayed on downloaded file on client side.

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
        response.TransmitFile(Server.MapPath("~/FileTemplates/Template.xlsx"));
        response.Flush();
        response.End();
    }
        public static void Download(string FilePath)
        {
            var    divider  = FilePath.LastIndexOf("/");
            String FileName = FilePath.Substring(divider + 1);


            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet; // "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath);
            response.Flush();
            response.End();
        }
Exemple #24
0
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        //Response.Redirect("Uploade/xml_0");

        string FileName = "xml.xml"; // It's a file name displayed on downloaded file on client side.

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/xml";
        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
        response.TransmitFile(Server.MapPath("~/Uploads/xml_0"));
        response.Flush();
        response.End();
    }
Exemple #25
0
        //HELPER FUNCTIONS//

        //User save dialog method
        public void dialog(string conType, string path, string name)
        {
            //Open dialog so that the user can save their file
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = conType;
            response.AddHeader("Content-Disposition", "attachment; filename=" + name + ";");
            response.TransmitFile(path + name);
            response.Flush();

            message = null;
            File.Delete(path + name);

            return;
        }
 protected void btnDownload_Click(object sender, EventArgs e)
 {
     if (gvMain.SelectedRow != null)
     {
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.ClearContent();
         response.Clear();
         string[] FileName = gvMain.SelectedRow.Cells[2].Text.ToString().Split('/');
         response.ContentType = "text/plain";
         response.AddHeader("Content-Disposition",
                            "attachment; filename=" + FileName[3] + ";");
         response.TransmitFile(Server.MapPath(gvMain.SelectedRow.Cells[2].Text));
         response.Flush();
         response.End();
     }
 }
Exemple #27
0
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            string fileName = request.QueryString["fileName"];
            string fileDest = request.QueryString["fileDest"];

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + fileName + ";");
            response.TransmitFile(fileDest);
            response.Flush();
            response.End();
        }
        protected void lnk_Click(object sender, EventArgs e)
        {
            string strFileName   = "CalendarManual.pdf";
            string strSourceFile = string.Empty;

            strSourceFile = Server.MapPath("~/Manual/CalendarManual.pdf");
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + strFileName + ";");
            response.TransmitFile(strSourceFile);
            response.Flush();
            response.End();
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //Save a trial user to the database
                string version = ConfigurationManager.AppSettings["Version"];

                if (string.IsNullOrEmpty(version))
                {
                    //throw error and return
                    return;
                }

                string trialDownloadPath = "~\\Releases\\" + version + "\\Downloadables\\Trial\\SimpleSqlite.zip";

                //Transmit the files
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.ClearContent();
                response.Clear();
                response.ContentType = "text/plain";
                response.AddHeader("Content-Disposition", "attachment; filename=SimpleSqlite.zip;");
                response.TransmitFile(trialDownloadPath);


                TrialUser trialUser = new SqlDatabaseManager.SimpleSqlite.TrialUser();
                trialUser.Email   = "*****@*****.**";
                trialUser.Name    = "test name";
                trialUser.Version = ConfigurationManager.AppSettings["Version"];

                ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["SimpleSqliteDatabaseConnString"];

                if (connectionStringSettings == null || string.IsNullOrEmpty(connectionStringSettings.ConnectionString))
                {
                    //throw error and return
                    return;
                }

                Database.TrialDatabase.AddTrialUser(trialUser, connectionStringSettings.ConnectionString);

                response.Flush();
                response.End();
            }
            catch (Exception ex)
            {
                //Pop up dialog to let user know an error occurred
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            string fileCode = request.QueryString["fileCode"];

            Dictionary <string, string> FileInfoDict = Find_File_Info(context, fileCode);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + FileInfoDict["fileName"] + ";");
            response.TransmitFile(context.Server.MapPath(FileInfoDict["filePath"]));
            response.Flush();
            response.End();
        }
Exemple #31
0
        public static bool DownloadFile(HttpResponse Response, HttpRequest Request, string filePath, string outputFileName, bool responseEnd,bool clearCache)
        {
            try
            {
                Response.ClearContent();

                string fileExtension = Path.GetExtension(outputFileName).ToLower();
                switch (fileExtension)
                {
                    case ".gif":
                        Response.ContentType = "image/gif";
                        break;
                    case ".swf":
                    case ".flv":
                        Response.ContentType = "application/x-shockwave-flash";
                        break;
                    case ".rmvb":
                    case ".rm":
                        Response.ContentType = "audio/x-pn-realaudio";
                        break;
                    case ".mp3":
                    case ".mpeg":
                    case ".mpg":
                        Response.ContentType = "audio/mpeg";
                        break;
                    case ".wav":
                        Response.ContentType = "audio/x-wav";
                        break;
                    case ".ra":
                        Response.ContentType = "audio/x-realaudio";
                        break;
                    case ".avi":
                        Response.ContentType = "video/x-msvideo";
                        break;
                    case ".mov":
                        Response.ContentType = "video/quicktime";
                        break;
                    default:
                        Response.ContentType = "application/octet-stream";
                        break;
                }

                // �ļ���
                //
                if (!string.IsNullOrEmpty(outputFileName))
                {
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(outputFileName)));
                }
                Response.TransmitFile(filePath);
                if (clearCache)
                {
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.Cache.SetNoStore();
                }
                if (responseEnd)
                    Response.End();
            }
            catch
            {
                return false;
            }
            return true;

        }
 protected override void WriteFile(HttpResponse response)
 {
     response.AddHeader("Content-Length", new FileInfo(FileName).Length.ToString());
     response.TransmitFile(FileName);
 }
        public bool Transmit(HttpResponse response, string sprocketPath)
        {
            CacheItemInfo info = null;
            bool memCached;
            lock (sprocketPathMemoryCache)
                memCached = sprocketPathMemoryCache.TryGetValue(sprocketPath, out info);
            if (info != null)
                info = ValidateCacheItem(info);

            if (info == null)
            {
                info = CheckDBForSprocketPath(sprocketPath);
                if (info == null)
                    return false;
                lock (sprocketPathMemoryCache)
                    sprocketPathMemoryCache[sprocketPath] = info;
            }
            if (!File.Exists(info.PhysicalPath))
            {
                if (memCached)
                    lock (sprocketPathMemoryCache)
                        sprocketPathMemoryCache.Remove(sprocketPath);
                return false;
            }
            response.ContentType = info.ContentType;
            response.TransmitFile(info.PhysicalPath);
            return true;
        }
        public static void ForceDownload(string FilePath, HttpResponse objResponse)
        {
            string strType = null;

            string strName = Path.GetFileName(FilePath);
            string strExt = Path.GetExtension(FilePath).ToLower();

            //Set Content Type for Response
            switch (strExt)
            {
                case ".htm":
                case ".html":
                    strType = "text/HTML";
                    break;
                case ".txt":
                    strType = "text/plain";
                    break;
                case ".rtf":
                    strType = "application/rtf";
                    break;
                case ".csv":
                    strType = "Application/x-msexcel";
                    break;
                case ".pdf":
                    strType = "application/pdf";
                    break;
                case ".asf":
                    strType = "video/x-ms-asf";
                    break;
                case ".avi":
                    strType = "video/avi";
                    break;
                case ".doc":
                    strType = "application/msword";
                    break;
                case ".zip":
                    strType = "application/zip";
                    break;
                case ".xls":
                    strType = "application/vnd.ms-excel";
                    break;
                case ".gif":
                    strType = "image/gif";
                    break;
                case ".jpg":
                case "jpeg":
                    strType = "image/jpeg";
                    break;
                case ".wav":
                    strType = "audio/wav";
                    break;
                case ".mp3":
                    strType = "audio/mpeg3";
                    break;
                case ".mpg":
                case "mpeg":
                    strType = "video/mpeg";
                    break;
                case ".asp":
                    strType = "text/asp";
                    break;
                default:
                    //Handle All Other Files
                    strType = "application/octet-stream";
                    break;
            }

            objResponse.ContentType = strType;
            objResponse.AppendHeader("content-disposition", "attachment; filename=" + strName);

            objResponse.TransmitFile(FilePath);
            objResponse.End();
        }
Exemple #35
0
        /// <summary>
        /// Writes the requested file from the package directly to the response.
        /// This method clears the response before sending the file and provides an option to skip 
        /// package validation.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="response"></param>
        /// <param name="skipValidation"></param>
        internal void TransmitFile(string filePath, HttpResponse response, bool skipValidation)
        {
            Utilities.ValidateParameterNonNull("filePath", filePath);
            Utilities.ValidateParameterNotEmpty("filePath", filePath);
            Utilities.ValidateParameterNonNull("response", response);

            if (!skipValidation)
            {
                using (ImpersonateIdentity id = new ImpersonateIdentity(m_impersonationBehavior))
                {
                    // If user does not have access, a UnauthorizedAccess Exception is thrown
                    Directory.GetFiles(m_packageBasePath);
                    // Check if package has valid e-learning content
                    if (!ManifestExists())
                        throw new InvalidPackageException(Resources.ImsManifestXmlMissing);
                }
            }

            string absoluteFilePath = SafePathCombine(m_packageBasePath, filePath);
            response.Clear();
            response.Buffer = false;
            response.BufferOutput = false;
            using (ImpersonateIdentity id = new ImpersonateIdentity(m_impersonationBehavior))
            {
                response.TransmitFile(absoluteFilePath);
            }
        }
Exemple #36
0
		public void TransmitFile_PermitOnly_FileIOPermission ()
		{
			HttpResponse response = new HttpResponse (writer);
			response.TransmitFile (fname);
		}
    /// <summary>
    /// Bietet die geforderte Datei zum Download an.
    /// </summary>
    /// <param name="file"></param>
    private void DownloadFile(HttpRequest request, HttpResponse response, ModuleConfig cfg, string file, bool asAttachment)
    {
      // Ermitteln des Filewappers der entsprechenden Datei.
      ConfigAgent cfgAgent = new ConfigAgent(cfg);
      FileWrapper dwnFile = cfgAgent.RootDirectory.GetFile(file);

      if (dwnFile != null)
      {
        response.CacheControl = "public";
        response.Cache.SetCacheability(HttpCacheability.Private);
        if (asAttachment)
          response.AddHeader("Content-Disposition", "attachment; filename=" + dwnFile.FileName);
        response.AddHeader("Content-Length", dwnFile.FileSize.ToString());
        String mimeType = dwnFile.MimeType;
        if (mimeType != null)
          response.ContentType = mimeType;
        response.TransmitFile(dwnFile.PhysicalPath);

        if(!Portal.API.Statistics.StatisticHelper.IsBot(request))
        {
          // In der Statistik zwischenspeichern.
          Statistic FbStatistic = new Statistic(cfgAgent.PhysicalRoot);
          FbStatistic.DownloadFile(file);
        }
      }
      else
        throw new FileNotFoundException();
    }
Exemple #38
0
 /// <summary>
 /// Writes an image to the response.
 /// </summary>
 /// <param name="path">The path of the file.</param>
 /// <param name="response">The HttpResponse to write to.</param>
 static void WriteNewImage(string path, HttpResponse response)
 {
     response.ContentType = "image/jpeg";
     response.TransmitFile(path);
 }
        public ResponseState ProcessDownload(HttpResponse objResponse)
        {
            ResponseState resultState = ResponseState.None;

            // Long Arrays for Range values:
            // ...Begin() contains start positions for each requested Range
            long[] alRequestedRangesBegin = new long[1];
            alRequestedRangesBegin[0] = _responseData.RangeBegin;

            // ...End() contains end positions for each requested Range
            long[] alRequestedRangesEnd = new long[1];
            alRequestedRangesEnd[0] = _responseData.RangeEnd;

            // Response Header value: Content Length...
            int iResponseContentLength = 0;

            // The Stream we//re using to download the file in chunks...
            System.IO.Stream objStream;
            // Total Bytes to read (per requested range)
            int iBytesToRead;

            // Size of the Buffer for chunk-wise reading
            int iBufferSize = 5120;

            // The Buffer itself
            byte[] bBuffer = new byte[iBufferSize];
            // Amount of Bytes read
            int iLengthOfReadChunk = -1;

            // Indicates if the download was interrupted
            bool bDownloadBroken = false;

            // Indicates if this is a multipart range request
            bool bMultipart = false;

            // Loop counter used to iterate through the ranges
            int iLoop;

            // Content-Disposition value
            string Content_Disposition_File = "attachment; filename=" + _responseData.FileHeaderName;

            if (!(_responseData.HttpMethod.Equals(HTTP_METHOD_GET) ||
                _responseData.HttpMethod.Equals(HTTP_METHOD_HEAD)))
                // Currently, only the GET and HEAD methods
                // are supported...
                objResponse.StatusCode = 501;  // Not implemented
            else
            {
                // Preliminary checks where successful...
                if (_responseData.RangeRequest)
                {
                    // This is a Range request...

                    // if the Range arrays contain more than one entry,
                    // it even is a multipart range request...
                    bMultipart = (alRequestedRangesBegin.GetUpperBound(0) > 0);

                    // Loop through each Range to calculate the entire Response length
                    for (iLoop = alRequestedRangesBegin.GetLowerBound(0); iLoop <= alRequestedRangesBegin.GetUpperBound(0); iLoop++)
                    {
                        // The length of the content (for this range)
                        iResponseContentLength += Convert.ToInt32(alRequestedRangesEnd[iLoop] - alRequestedRangesBegin[iLoop]) + 1;

                        if (bMultipart)
                        {
                            //
                            iResponseContentLength += HTTP_HEADER_Content_Disposition.Length;
                            // if this is a multipart range request, calculate
                            // the length of the intermediate headers to send
                            iResponseContentLength += MULTIPART_BOUNDARY.Length;
                            iResponseContentLength += _responseData.ContentType.Length;
                            iResponseContentLength += alRequestedRangesBegin[iLoop].ToString().Length;
                            iResponseContentLength += alRequestedRangesEnd[iLoop].ToString().Length;

                            // DataLength = Total size
                            iResponseContentLength += _responseData.DataLength.ToString().Length;

                            // 49 is the length of line break and other
                            // needed characters in one multipart header
                            iResponseContentLength += 49;
                        }

                    }

                    if (bMultipart)
                    {
                        // if this is a multipart range request,
                        // we must also calculate the length of
                        // the last intermediate header we must send
                        iResponseContentLength += MULTIPART_BOUNDARY.Length;
                        // 8 is the length of dash and line break characters
                        iResponseContentLength += 8;
                    }
                    else
                    {
                        // This is no multipart range request, so
                        // we must indicate the response Range of
                        // in the initial HTTP Header
                        // DataLength = Total size
                        objResponse.AppendHeader(HTTP_HEADER_CONTENT_RANGE, "bytes " +
                            alRequestedRangesBegin[0].ToString() + "-" +
                            alRequestedRangesEnd[0].ToString() + "/" +
                            _responseData.DataLength.ToString());
                    }

                    // Range response
                    objResponse.StatusCode = 206; // Partial Response

                }
                else
                {
                    // This is not a Range request, or the requested Range entity ID
                    // does not match the current entity ID, so start a new download

                    // Indicate the file's complete size as content length
                    // DataLength = Total size
                    iResponseContentLength = Convert.ToInt32(_responseData.DataLength);

                    // Return a normal OK status...
                    objResponse.StatusCode = 200;
                }

                // Write file name into the Response
                objResponse.AppendHeader(HTTP_HEADER_Content_Disposition, Content_Disposition_File);

                // Write the content length into the Response
                objResponse.AppendHeader(HTTP_HEADER_CONTENT_LENGTH, iResponseContentLength.ToString());

                // Write the Last-Modified Date into the Response
                objResponse.AppendHeader(HTTP_HEADER_LAST_MODIFIED, _responseData.LastWriteTimeUTC.ToString("r"));

                // Tell the client software that we accept Range request
                objResponse.AppendHeader(HTTP_HEADER_ACCEPT_RANGES, HTTP_HEADER_ACCEPT_RANGES_BYTES);

                // Write the file//s Entity Tag into the Response (in quotes!)
                objResponse.AppendHeader(HTTP_HEADER_ENTITY_TAG, "\"" + _responseData.EntityTag + "\"");

                // Write the Content Type into the Response
                if (bMultipart)
                    // Multipart messages have this special Type.
                    // In this case, the file//s actual mime type is
                    // written into the Response at a later time...
                    objResponse.ContentType = MULTIPART_CONTENTTYPE;
                else
                    // Single part messages have the files content type...
                    objResponse.ContentType = _responseData.ContentType;

                if (_responseData.HttpMethod.Equals(HTTP_METHOD_HEAD))
                {
                    // Only the HEAD was requested, so we can quit the Response right here...
                }
                else
                {
                    // Flush the HEAD information to the client...
                    objResponse.Flush();

                    // Download is in progress...
                    resultState = ResponseState.InProgress;

                    // The steram
                    objStream = _responseData.DataStream;

                    if (!_responseData.ApplyRangeToStream)
                    {
                        // first range only
                        iLoop = 0;

                        // Calculate the total amount of bytes for first range only
                        iBytesToRead = Convert.ToInt32(alRequestedRangesEnd[iLoop] - alRequestedRangesBegin[iLoop]) + 1;

                        // sending header for multipart request
                        if (bMultipart)
                        {
                            // if this is a multipart response, we must add
                            // certain headers before streaming the content:

                            // The multipart boundary
                            objResponse.Output.WriteLine("--" + MULTIPART_BOUNDARY);

                            // The mime type of this part of the content
                            objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_TYPE + ": " + _responseData.ContentType);

                            // The actual range
                            // // DataLength = Total size
                            objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_RANGE + ": bytes " +
                                alRequestedRangesBegin[iLoop].ToString() + "-" +
                                alRequestedRangesEnd[iLoop].ToString() + "/" +
                                _responseData.DataLength.ToString());

                            // Indicating the end of the intermediate headers
                            objResponse.Output.WriteLine();
                        }

                        // flush the data

                        // Declare variables
                        int readed = -1;

            #if dotNET20sp1
                        if (_responseData.IsDataFile)
                        {
                            // send file content directly
                            objResponse.TransmitFile(_responseData.FileName);
                        }
                        else
            #endif
                        // Get the response stream for reading
                        // Read the stream and write it into memory
                        while ((int)(readed = objStream.Read(bBuffer, 0, bBuffer.Length)) > 0)
                        {
                            if (objResponse.IsClientConnected)
                            {
                                // write to response
                                objResponse.OutputStream.Write(bBuffer, 0, readed);

                                // send response
                                objResponse.Flush();
                            }
                            else
                            {
                                bDownloadBroken = true;
                                break;
                            }
                        }

                        // In Multipart responses, mark the end of the part
                        if (bMultipart)
                            objResponse.Output.WriteLine();

                        // No need to proceed to the next part if the
                        // client was disconnected
                        if (bDownloadBroken)
                        {
                            //break;
                        }
                        // done!
                    }
                    else
                    {
                        // Now, for each requested range, stream the chunks to the client:
                        for (iLoop = alRequestedRangesBegin.GetLowerBound(0); iLoop <= alRequestedRangesBegin.GetUpperBound(0); iLoop++)
                        {
                            // Move the stream to the desired start position...
                            objStream.Seek(alRequestedRangesBegin[iLoop], SeekOrigin.Begin);

                            // Calculate the total amount of bytes for this range
                            iBytesToRead = Convert.ToInt32(alRequestedRangesEnd[iLoop] - alRequestedRangesBegin[iLoop]) + 1;

                            if (bMultipart)
                            {
                                // if this is a multipart response, we must add
                                // certain headers before streaming the content:

                                // The multipart boundary
                                objResponse.Output.WriteLine("--" + MULTIPART_BOUNDARY);

                                // The mime type of this part of the content
                                objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_TYPE + ": " + _responseData.ContentType);

                                // The actual range
                                // // DataLength = Total size
                                objResponse.Output.WriteLine(HTTP_HEADER_CONTENT_RANGE + ": bytes " +
                                    alRequestedRangesBegin[iLoop].ToString() + "-" +
                                    alRequestedRangesEnd[iLoop].ToString() + "/" +
                                    _responseData.DataLength.ToString());

                                /*objResponse.AppendHeader(HTTP_HEADER_CONTENT_RANGE,": bytes " +
                                    alRequestedRangesBegin[iLoop].ToString() + "-" +
                                    alRequestedRangesend[iLoop].ToString() + "/" +
                                    objFile.Length.ToString());
                                */
                                // Indicating the end of the intermediate headers
                                objResponse.Output.WriteLine();

                            }

            #if dotNET20sp1
                            if (_responseData.IsDataFile)
                            {
                                // send file content directly
                                objResponse.TransmitFile(_responseData.FileName, alRequestedRangesBegin[iLoop], iBytesToRead);
                            }
                            else
            #endif
                            // Now stream the range to the client...
                            while (iBytesToRead > 0)
                            {

                                if (objResponse.IsClientConnected)
                                {
                                    // Read a chunk of bytes from the stream
                                    iLengthOfReadChunk = objStream.Read(bBuffer, 0, Math.Min(bBuffer.Length, iBytesToRead));

                                    // Write the data to the current output stream.
                                    objResponse.OutputStream.Write(bBuffer, 0, iLengthOfReadChunk);

                                    // Flush the data to the HTML output.
                                    objResponse.Flush();

                                    // Clear the buffer
                                    //bBuffer=new byte[iBufferSize];

                                    // Reduce BytesToRead
                                    iBytesToRead -= iLengthOfReadChunk;
                                }
                                else
                                {
                                    // The client was or has disconneceted from the server... stop downstreaming...
                                    iBytesToRead = -1;
                                    bDownloadBroken = true;
                                }
                            }

                            // In Multipart responses, mark the end of the part
                            if (bMultipart)
                                objResponse.Output.WriteLine();

                            // No need to proceed to the next part if the
                            // client was disconnected
                            if (bDownloadBroken)
                                break;
                        }
                    }
                    // At this point, the response was finished or cancelled...

                    if (bDownloadBroken)
                        // Download is broken...
                        resultState = ResponseState.Broken;
                    else
                    {
                        if (bMultipart)
                        {
                            // In multipart responses, close the response once more with
                            // the boundary and line breaks
                            objResponse.Output.WriteLine("--" + MULTIPART_BOUNDARY + "--");
                            objResponse.Output.WriteLine();
                        }

                        // The download was finished
                        resultState = ResponseState.Finished;
                    }

                    // the data stream now can be closed
                    objStream.Close();
                }
            }

            //====== return download state ======
            return resultState;
        }
        private void TransmitFileUsingHttpResponse(HttpRequest request, HttpResponse response,
            string physicalFilePath, ResponseCompressionType compressionType, FileInfo file)
        {
            if (file.Exists)
            {
                // We don't cache/compress such file types. Must be some binary file that's better
                // to let IIS handle
                this.ProduceResponseHeader(response, Convert.ToInt32(file.Length), compressionType,
                    physicalFilePath, file.LastWriteTimeUtc);
                response.TransmitFile(physicalFilePath);

                Debug.WriteLine("TransmitFile: " + request.FilePath);
            }
            else
            {
                throw new HttpException((int)HttpStatusCode.NotFound, request.FilePath + " Not Found");
            }
        }
		public bool TrySendResponseOrStartResponseCapture(HttpResponse response)
		{
			byte[] responseData = null;
			string responseFile = null;

			// loop while trying to either send or capture the response
			// (the loop is needed for cases when another thread does the capture)
			for (; ; )
			{

				lock (this)
				{
					// attempt to find the cached response on disk (only once)
					if (!_triedToLoadCachedResponse)
					{
						LookForCachedResponseOnDisk();
						_triedToLoadCachedResponse = true;
					}

					if (_cachedResponseLoaded && ValidateLoadedCachedResponse())
					{
						// serve the cached response if validated
						if (_serveFromMemory)
						{
							responseData = _cachedResponseBytes;
						}
						else
						{
							responseFile = _dataFilename;
						}

						// send the response outside of the lock
						break;
					}

					// couldn't send the response - try to capture it under lock
					// (don't attempt to capture the same response from 2 threads at the same time)
					if (_capturingResponse == null)
					{
						// generate new file name
						string filename = string.Format("{0}_{1:x8}{2}",
								_filenamePrefix, Guid.NewGuid().ToString().GetHashCode(), TempFileExt);

						_capturingFilter = new ResponseFilter(response.Filter, filename);
						response.Filter = _capturingFilter;

						// move the event - non-signaled state
						_capturingEvent.Reset();
						// remember the response
						_capturingResponse = response;
						// started capturing - return from this method
						break;
					}
				}

				// capturing started from another thread - wait until done and continue (outside of the lock)
				_capturingEvent.WaitOne();
			}

			// send the cached response if available (outside of the lock)
			if (responseData != null)
			{
				response.OutputStream.Write(responseData, 0, responseData.Length);
				return true;
			}
			else if (responseFile != null)
			{
				try
				{
					response.TransmitFile(responseFile);
				}
				catch
				{
					// if there is a problem sending data file, invalidate the cached response
					InvalidateCachedResponse();
					throw;
				}

				return true;
			}
			else
			{
				return false;
			}
		}
 public static void DownLoadFileByByteEX(byte[] buffers, HttpResponse response, string fileName, string filePath)
 {
     response.Clear();
     response.ClearContent();
     response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
     response.AppendHeader("Content-Length ", buffers.Length.ToString());
     response.ContentType = "application/pdf";
     response.TransmitFile(filePath);
     //response.Flush();
     //response.End();
 }
Exemple #43
0
 private static Func<string, long, long?, CancellationToken, Task> CreateSendFileFunc(HttpResponse response)
 {
     return (path, offset, byteCount, cancel) =>
     {
         var length = byteCount.HasValue ? byteCount.Value : -1;
         response.TransmitFile(path, offset, length);
         return TaskHelper.Completed();
     };
 }