当前位置: 首页>>代码示例>>C#>>正文


C# HttpResponse.BinaryWrite方法代码示例

本文整理汇总了C#中System.Web.HttpResponse.BinaryWrite方法的典型用法代码示例。如果您正苦于以下问题:C# HttpResponse.BinaryWrite方法的具体用法?C# HttpResponse.BinaryWrite怎么用?C# HttpResponse.BinaryWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.HttpResponse的用法示例。


在下文中一共展示了HttpResponse.BinaryWrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetImage

        public void GetImage(HttpResponse reponse, int id)
        {
            using (SqlConnection connection = new SqlConnection("Data Source=DESKTOP-5A9RHHB;Initial Catalog=EcommerceSimplifie; Integrated Security=True"))
            {
                //try
                //{
                SqlCommand command = new SqlCommand("select Picture.PictureBinary, Picture.MimeType from Picture inner join Product_Picture_Mapping on Picture.Id = Product_Picture_Mapping.PictureId where ProductId = @id and DisplayOrder = 1;");
                command.Connection = connection;
                command.Parameters.Add(new SqlParameter("@id", id));

                connection.Open();

                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {

                    //type de l'image
                    string typeMime = reader.GetString(1);
                    reponse.ContentType = (string.IsNullOrEmpty(typeMime)) ? "image/jpeg" : typeMime;

                    //mise en cache
                    reponse.Cache.SetCacheability(HttpCacheability.Public);

                    int indexDepart = 0;
                    int tailleBuffer = 1024;
                    long nombreOctets = 0;
                    Byte[] flux = new Byte[1024];

                    nombreOctets = reader.GetBytes(0, indexDepart, flux, 0, tailleBuffer);

                    while (nombreOctets == tailleBuffer)
                    {
                        reponse.BinaryWrite(flux);
                        reponse.Flush();
                        indexDepart += tailleBuffer;
                        nombreOctets = reader.GetBytes(0, indexDepart, flux, 0, tailleBuffer);
                    }
                    if (nombreOctets > 0)
                    {
                        reponse.BinaryWrite(flux);
                        reponse.Flush();
                    }
                    reponse.End();

                }
                //catch(Exception)
                //{
                //    throw new Exception("Pas d'image disponible.");
                //}
                //}
            }
        }
开发者ID:boule46,项目名称:activite_git,代码行数:53,代码来源:HandlerImage.cs

示例2: DataTableToExcel

        /// <summary>
        /// Datatable数据填充如excel
        /// </summary>
        /// <param name="filename">excel文件名</param>
        /// <param name="dt"> 数据源</param>
        /// <param name="Response"> response响应</param>
        ///  <param name="headerStr"> 表头标题</param>
        public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr)
        {
            MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream  as用作转换,此处可以省略
            try
            {

                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.ContentEncoding = Encoding.UTF8;
                Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls"));
                Response.AddHeader("content-length", ms.Length.ToString());
                Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组
                Response.BinaryWrite(data);
            }
            catch
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>");
            }
            Response.Flush();
            Response.Close();
            Response.End();
            ms = null;
        }
开发者ID:mildrock,项目名称:wechat,代码行数:32,代码来源:NPOIHelper.cs

示例3: Process

 public void Process(HttpResponse response)
 {
     response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r"));
     response.AppendHeader("ETag", serverFingerprint.ETag);
     response.AppendHeader("Cache-Control", "private, max-age=0");
     response.BinaryWrite(content);
 }
开发者ID:kascomp,项目名称:CruiseControl.NET,代码行数:7,代码来源:BinaryResponse.cs

示例4: DownFile

 public static bool DownFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
 {
     try
     {
         FileStream input = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         BinaryReader reader = new BinaryReader(input);
         try
         {
             _Response.AddHeader("Accept-Ranges", "bytes");
             _Response.Buffer = false;
             long length = input.Length;
             long num2 = 0L;
             int count = 0x2800;
             double d = ((long) (0x3e8 * count)) / _speed;
             int millisecondsTimeout = ((int) Math.Floor(d)) + 1;
             if (_Request.Headers["Range"] != null)
             {
                 _Response.StatusCode = 0xce;
                 num2 = Convert.ToInt64(_Request.Headers["Range"].Split(new char[] { '=', '-' })[1]);
             }
             _Response.AddHeader("Content-Length", (length - num2).ToString());
             if (num2 != 0L)
             {
                 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", num2, length - 1L, length));
             }
             _Response.AddHeader("Connection", "Keep-Alive");
             _Response.ContentType = "application/octet-stream";
             _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, Encoding.UTF8));
             reader.BaseStream.Seek(num2, SeekOrigin.Begin);
             double num6 = (length - num2) / ((long) count);
             int num7 = ((int) Math.Floor(num6)) + 1;
             for (int i = 0; i < num7; i++)
             {
                 if (_Response.IsClientConnected)
                 {
                     _Response.BinaryWrite(reader.ReadBytes(count));
                     Thread.Sleep(millisecondsTimeout);
                 }
                 else
                 {
                     i = num7;
                 }
             }
         }
         catch
         {
             return false;
         }
         finally
         {
             reader.Close();
             input.Close();
         }
     }
     catch
     {
         return false;
     }
     return true;
 }
开发者ID:SoMeTech,项目名称:SoMeRegulatory,代码行数:60,代码来源:file.cs

示例5: GetImageFromFile

        //defaultfile is under userpath
        public static void GetImageFromFile(string filename,string defaultfile,HttpResponse response)
        {
            if (!File.Exists(filename))
            {
                string userdatapath = Functions.GetAppConfigString("UserDataPath", "");
                filename = userdatapath + "\\"+defaultfile;
            }

            System.IO.FileStream fs = null;
            System.IO.MemoryStream ms = null;
            try
            {

                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                ms = new System.IO.MemoryStream(buffer);

                response.ClearContent();
                response.BinaryWrite(ms.ToArray());
                ms.Close();

            }
            finally
            {
                fs.Dispose();
                ms.Dispose();

            }
        }
开发者ID:kissmettprj,项目名称:col,代码行数:33,代码来源:CommonBLL.cs

示例6: Write

        /// <summary>
        /// Writes the result directly into the response stream, e.g. for a classic ASP.NET response
        /// </summary>
        /// <param name="response">A standard HttpResponse object</param>
        /// <param name="result">An IBackloadResult object</param>
        public static void Write(HttpResponse response, IBackloadResult result)
        {

            response.StatusCode = (int)result.HttpStatusCode;
            if ((int)result.HttpStatusCode < 300)
            {

                // Write result to the response (Json or file data, default: Json response)
                if (result.RequestType == RequestType.Default)
                {
                    // Json response (We use the systems JavaScriptSerializer, you can also use Newtonsoft.Json)
                    IFileStatusResult status = (IFileStatusResult)result;
                    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                    if ((status.ClientStatus != null) && (result.Exception == null))
                        response.Write(serializer.Serialize(status.ClientStatus));
                }
                else if ((result.RequestType == RequestType.File) || (result.RequestType == RequestType.Thumbnail))
                {
                    // file data (byte array) response
                    IFileDataResult data = (IFileDataResult)result;

                    if ((data.FileData != null) && (result.Exception == null))
                        response.BinaryWrite(data.FileData);
                }
            }
        }
开发者ID:rj-max,项目名称:Backload,代码行数:32,代码来源:ResultCreator.Classic.cs

示例7: SendToResponse

 /// <summary>
 /// Sends the file to the response with content-length header
 /// Works with all types of files, not image specific
 /// </summary>
 /// <param name="response"></param>
 /// <param name="file"></param>
 /// <param name="mimetype"></param>
 private static void SendToResponse(HttpResponse response, byte[] fileContent, DateTime lastWriteTime, string mimetype)
 {
   response.ClearHeaders();
   setCacheHeaders(response);
   
   response.Cache.SetLastModified(lastWriteTime); // to avoid rounding problems with header (no millisecs there)
   response.ContentType = mimetype;      
   response.AppendHeader("Content-Length", fileContent.Length.ToString());
   response.BinaryWrite(fileContent);
   response.End();
 }
开发者ID:BaoToan94,项目名称:q42.wheels.gimmage,代码行数:18,代码来源:HttpImageServer.cs

示例8: ResponseFile

        public static bool ResponseFile(HttpRequest request, HttpResponse response, string fileName, string fullPath, long speed, string pageUrl)
        {
            FileStream myFile = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                response.AddHeader("Accept-Ranges", "bytes");
                response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                const int pack = 10240;
                int sleep = (int)Math.Floor((double)(1000 * pack / speed)) + 1;
                if (request.Headers["Range"] != null)
                {
                    response.StatusCode = 206;
                    string[] range = request.Headers["Range"].Split(new[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                response.AddHeader("Connection", "Keep-Alive");
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (response.IsClientConnected)
                    {
                        response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            finally
            {
                br.Close();
                myFile.Close();
            }

            return true;
        }
开发者ID:Christind,项目名称:ucn-3semproject-dm79-group1,代码行数:52,代码来源:FileHelper.cs

示例9: ToExcel

        public static void ToExcel(HttpResponse Response,DataTable dt , string fileName)
        {
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();

                //Add Header
                for (int count = 0; count < dt.Columns.Count - 1; count++)
                {
                    if (dt.Columns[count].ColumnName != null)
                        sb.Append(dt.Columns[count].ColumnName);
                    sb.Append("\t");
                }
                Response.Write(sb.ToString() + "\n");
                Response.Flush();

                //Append Data
                int index = 0;
                while (dt.Rows.Count >= index + 1)
                {
                    sb = new StringBuilder();

                    for (int col = 0; col < dt.Columns.Count -1; col++)
                    {
                        if (dt.Rows[index][col] != null)
                            //sb.Append(dt.Rows[index][col].ToString().Replace(",", " "));
                            sb.Append(dt.Rows[index][col].ToString());
                        sb.Append("\t");
                    }

                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    index = index + 1;
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

            dt.Dispose();
            Response.End();
        }
开发者ID:thanhphat,项目名称:ibookstop,代码行数:50,代码来源:Table2Excel.cs

示例10: RackHandleRequest

        public static void RackHandleRequest(HttpRequest request, HttpResponse response)
        {
            MyRackImage.BasePath = "Rack.Net.Tests/";

            IResponse call = rackApp.Call(ConvertToDicationary(request.Params));
            TransferHeader(response, call.Headers);
            if (call.Body.IsString())
            {
                response.Write(call.Body.ToString());
            }
            else
            {
                response.BinaryWrite(call.Body.ToBytes());
            }
        }
开发者ID:sware,项目名称:racknet,代码行数:15,代码来源:RackHandler.cs

示例11: ProcessResponse

 /// <summary>
 /// 
 /// </summary>
 /// <param name="httpResponse"></param>
 /// <param name="body"></param>
 protected void ProcessResponse(HttpResponse httpResponse, ResponseBody body)
 {
     try
     {
         SetResponseHead(httpResponse);
         var buffer = ResponseFormater.Serialize(body);
         httpResponse.BinaryWrite(buffer);
     }
     catch (Exception error)
     {
         TraceLog.WriteError("Response handle error:{0}", error);
         httpResponse.StatusCode = 500;
         httpResponse.StatusDescription = "Response error.";
     }
 }
开发者ID:huangbenyu,项目名称:Scut,代码行数:20,代码来源:BaseHttpHandler.cs

示例12: GenerateCsvResponse

        internal static void GenerateCsvResponse(HttpResponse response, string formName, string data)
        {
            Assert.ArgumentNotNull(response, "response");
            Assert.ArgumentNotNullOrEmpty(formName, "formName");
            Assert.ArgumentNotNullOrEmpty(data, "data");

            response.Clear();
            response.ContentType = Constants.Response.ContentType.Csv;
            response.AddHeader(Constants.Response.Header.ContentDisposition.Name,
                string.Format(Constants.Response.Header.ContentDisposition.AttachmentFilenameFormat,
                    GenerateFileNameService.GenerateFileName(formName)));
            response.Charset = Constants.Response.Charset.Utf8;
            response.BinaryWrite(Encoding.UTF8.GetPreamble());
            response.Write(data);
            response.End();
        }
开发者ID:ptiemann,项目名称:WFFM-SQL-Server-SaveToDatabase,代码行数:16,代码来源:GenerateCsvResponseService.cs

示例13: Dowload

 /// <summary>
 /// 保存报表文件为文件
 /// </summary>
 /// <param name="rpvObject">Reportview控件实例</param>
 /// <param name="rptType">打印的文件类型</param>
 /// <param name="filePath">文件存放路径</param>
 /// <param name="fileName">文件名</param>
 public static void Dowload(HttpResponse response, string filePath, string fileName, string extension)
 {
     if (response == null || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(extension)) return;
     FileStream stream = new FileStream(filePath + fileName + "." + extension, FileMode.Open);
     byte[] bytes = new byte[stream.Length];
     stream.Read(bytes, 0, bytes.Length);
     // 设置当前流的位置为流的开始
     stream.Seek(0, SeekOrigin.Begin);
     stream.Close();
     //Download
     response.Buffer = true;
     response.Clear();
     response.ContentType = "application/" + extension;
     response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + extension);
     response.BinaryWrite(bytes);
     response.Flush();
     response.End();
 }
开发者ID:gettogether,项目名称:common-object,代码行数:25,代码来源:RdlcDownloadHelper.cs

示例14: imprimirReciboPDF

        public void imprimirReciboPDF(int numRecibo, HttpResponse Response)
        {
            try
            {
                DataSet dsRec = new DataSet("DataSetRec");
                DataTable dt = new DataTable("DataTableRec");
                FacturasRN ds = new FacturasRN();
                dsRec.Tables.Add(dt);

                ds.getRecibos(ref dt, numRecibo);
                ReportDataSource rds = new ReportDataSource();
                rds.Name = "DataSetRec_DataTableRec";
                rds.Value = dsRec.Tables[0];
                ReportViewer ReportViewer1 = new ReportViewer();
                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.DataSources.Add(rds);
                ReportViewer1.LocalReport.ReportPath = "F:/EBuy/EbuyPlaceNet/FacturacionEbuy/Reportes/Recibo/Recibo_rpt.rdlc";
                //Dim p As New ReportParameter("TITULO", "DETALLE DEL LOTE " & Request.QueryString("id_lote") & " DE LA OBRA " & Request.QueryString("obra"))
                //ReportViewer1.LocalReport.SetParameters(New ReportParameter() {p})
                ReportViewer1.LocalReport.Refresh();
                string reportType = "PDF";
                string mimeType = "";
                string encoding = "";
                string fileNameExtension = "";

                string deviceInfo = "" + " PDF" + " 8.5in" + " 11in" + " 0.5in" + " 1in" + " 1in" + " 0.5in" + "";

                Warning[] Warnings = null;
                string[] streams = null;
                Byte[] renderedBytes;

                renderedBytes = ReportViewer1.LocalReport.Render(reportType, null, out mimeType, out encoding, out fileNameExtension, out streams, out Warnings);

                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=Recibo." + fileNameExtension);
                Response.BinaryWrite(renderedBytes);
                Response.End();
            }
            catch(Exception ex)
            {

            }
        }
开发者ID:marianoir,项目名称:ebuyplacenet,代码行数:44,代码来源:PrintRecibos.cs

示例15: WriteResponse

 public static void WriteResponse(HttpResponse response, byte[] filearray, string type)
 {
     response.ClearContent();
     response.Buffer = true;
     response.Cache.SetCacheability(HttpCacheability.Private);
     response.ContentType = "application/pdf";
     ContentDisposition contentDisposition = new ContentDisposition();
     contentDisposition.FileName = "SaldoDotacao.pdf";
     contentDisposition.DispositionType = type;
     response.AddHeader("Content-Disposition", contentDisposition.ToString());
     response.BinaryWrite(filearray);
     HttpContext.Current.ApplicationInstance.CompleteRequest();
     try
     {
         response.End();
     }
     catch (System.Threading.ThreadAbortException)
     {
     }
 }
开发者ID:EmersonBessa,项目名称:FluxusWeb,代码行数:20,代码来源:consultaSaldoDotacao.aspx.cs


注:本文中的System.Web.HttpResponse.BinaryWrite方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。