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


C# MemoryStream.Flush方法代码示例

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


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

示例1: SerializeToLocalStorage

        public static void SerializeToLocalStorage(this object value, string fullPath)
        {
            if (value == null)
                throw (new ArgumentNullException("Value cannot be NULL.", "value"));

            string file = null;
            string[] paths = fullPath.Split('\\');

            if (paths.Length < 1 || string.IsNullOrWhiteSpace(paths[0]))
                throw (new ArgumentException("This is not a valid path for LocalStorage.", "filename"));

            file = paths[paths.Length - 1];
            
            MemoryStream stream = new MemoryStream();
            
            DataContractSerializer serializer = new DataContractSerializer(value.GetType());
            serializer.WriteObject(stream, value);
            stream.Seek(0, SeekOrigin.Begin);

            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)stream.Length);

            File.WriteAllBytes(fullPath, buffer);

            stream.Flush();
            stream.Close();
        }
开发者ID:loic-lavergne,项目名称:mckineap,代码行数:27,代码来源:System.IO.IsolatedStorage.cs

示例2: BitMapToByte

    /// <summary>
    /// BitMap转换成二进制
    /// </summary>
    /// <param name="bitmap"></param>
    /// <returns></returns>
    public static byte[] BitMapToByte(Bitmap bitmap)
    {
        //List<byte[]> list = new List<byte[]>();
        MemoryStream ms = null;
        byte[] imgData = null;

        ///重新绘图并指定大小
        int destWidth = 794;
        int destHight = 1122;

        Bitmap newBitmap = new Bitmap(destWidth, destHight);
        using(Graphics g=Graphics.FromImage((Image)newBitmap))
        {
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.DrawImage((Image)bitmap, 0, 0, destWidth, destHight);
            g.Dispose();
        }

        ///

        using (ms = new MemoryStream())
        {
            newBitmap.Save(ms, ImageFormat.Jpeg);
            ms.Position = 0;
            imgData = new byte[ms.Length];
            ms.Read(imgData, 0, Convert.ToInt32(ms.Length));
            ms.Flush();
        }
        //list.Add(imgData);
        return imgData;
    }
开发者ID:hkis,项目名称:octopus,代码行数:38,代码来源:ImageTools.cs

示例3: Object2String

    public string Object2String(object o)
    {
        if (o == null) return null;

        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, o);
        ms.Flush();
        ms.Position = 0;

        byte[] data = new byte[ms.Length];
        ms.Read(data, 0, data.Length);
        ms.Close();

        MemoryStream stream = new MemoryStream();
        sf.Serialize(stream, data);
        stream.Flush();
        stream.Position = 0;

        StreamReader sr = new StreamReader(stream);
        string str = sr.ReadToEnd();
        sr.Close();
        stream.Close();

        return str;
    }
开发者ID:lakeli,项目名称:shizong,代码行数:25,代码来源:Searializer.cs

示例4: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        String qs = Request.QueryString.Get("bid");
        Response.Write("Query String = " + qs);
        SqlConnection sql = new SqlConnection();
        sql.ConnectionString = "Data Source=(local);Initial Catalog=Hotel;Integrated Security=True";
        sql.Open();

        ReportDocument rpd = new ReportDocument();
        rpd.Load(Server.MapPath("itcreport.rpt"));
        rpd.SetDatabaseLogon("sa", "ak");
        rpd.SetParameterValue(0, qs);
        CrystalReportViewer1.ReportSource = rpd;

        //to convert report in pdf format
        MemoryStream ostream = new MemoryStream();
        Response.Clear();
        Response.Buffer = true;
        ostream = (MemoryStream)rpd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        rpd.Close();
        rpd.Dispose();
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(ostream.ToArray());
        ostream.Flush();
        ostream.Close();
        ostream.Dispose();
    }
开发者ID:akshaykhanna,项目名称:Hotel-Booking-website,代码行数:27,代码来源:report.aspx.cs

示例5: PersonalDetailsView_DataBound

    protected void PersonalDetailsView_DataBound(object sender, EventArgs e)
    {
        byte[] photoByte = null;
        string photoExtn = ".jpeg";

        DataRow row = (ViewState["DataTable"] as DataTable).Rows[0];
        if (PersonalDetailsView.CurrentMode == DetailsViewMode.ReadOnly)
        {
            Label categoryLabel = PersonalDetailsView.Rows[0].FindControl("userIdLabel") as Label;
            Image img = PersonalDetailsView.Rows[0].FindControl("userImage") as Image;

            if (personalDetailsTable != null && categoryLabel != null)
            {
                photoByte = (byte[])row["image"];

                if (photoByte != null && photoByte.Length > 1)
                {
                    System.Drawing.Image newImage = null;
                    string fileName = GetTempFolderName() + categoryLabel.Text + photoExtn;
                    MemoryStream stream = new MemoryStream(photoByte);
                    newImage = System.Drawing.Image.FromStream(stream);
                    newImage.Save(fileName);
                    stream.Flush();
                    stream.Close();
                }
            }
        }
    }
开发者ID:shyam2293,项目名称:spencers,代码行数:28,代码来源:MyAccount.aspx.cs

示例6: Serialize

 public static string Serialize(StateCollection stateCollection)
 {
     using (MemoryStream stream = new MemoryStream()) {
         BinaryFormatter serializer = new BinaryFormatter();
         serializer.Serialize(stream, stateCollection);
         stream.Flush();
         stream.Position = 0;
         return Convert.ToBase64String(stream.ToArray());
     }
 }
开发者ID:redien,项目名称:Ludum-Dare-30,代码行数:10,代码来源:StateCollection.cs

示例7: RPCEx

	public static void RPCEx(this NetworkView view, string routineName, NetworkPlayer player, params object[] parameters)
	{
		using(var m = new MemoryStream())
		{
			var b = new BinaryFormatter();
			b.Serialize(m, parameters);
			m.Flush();
			var s = Convert.ToBase64String(m.GetBuffer());
			view.RPC("PerformRPCCall", player, routineName, s);
		}
	}
开发者ID:marcteys,项目名称:trauts,代码行数:11,代码来源:InheritableRPC.cs

示例8: getEncodedFileContent

    /*!
    \brief Get content of a file and encode it in UTF-8
    \param path The path of the file
       */
    public static MemoryStream getEncodedFileContent(string path)
    {
        StreamReader fileStream = new StreamReader(@path);
        string text = fileStream.ReadToEnd();
        fileStream.Close();
        byte[] encodedString = Encoding.UTF8.GetBytes(text);
        MemoryStream ms = new MemoryStream(encodedString);
        ms.Flush();
        ms.Position = 0;

        return ms;
    }
开发者ID:quito,项目名称:DSynBio_reloaded,代码行数:16,代码来源:Tools.cs

示例9: DecompressFileLZMA

    public static byte[] DecompressFileLZMA(byte[] inBytes)
    {
        SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder();
        var input = new MemoryStream(inBytes);
        var output = new MemoryStream();

        byte[] ret = null;


        try
        {
            // Read the decoder properties
            byte[] properties = new byte[5];
            input.Read(properties, 0, 5);

            // Read in the decompress file size.
            byte[] fileLengthBytes = new byte[8];
            input.Read(fileLengthBytes, 0, 8);
            long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);

            // Decompress the file.
            coder.SetDecoderProperties(properties);
            coder.Code(input, output, input.Length, fileLength, null);
            output.Flush();

            ret = output.GetBuffer();
        }
        catch
        {
            throw;
        }
        finally
        {
            output.Close();
            output.Dispose();
            input.Close();
            input.Dispose();

        }


        return ret;

    }
开发者ID:henry-yuxi,项目名称:CosmosEngine,代码行数:44,代码来源:CLzmaTool.cs

示例10: MemStreamClearWriteByteTest

 public static bool MemStreamClearWriteByteTest()
 {
     Console.WriteLine("Ensuring that we clear data > Length in a MemoryStream when we write past the end via WriteByte");
     const int len = 10;
     const int spanPastEnd = 5;
     MemoryStream ms = new MemoryStream(3*len);
     byte[] bytes = new byte[len];
     for(int i=0; i<bytes.Length; i++)
         bytes[i] = (byte) i;
     ms.Write(bytes, 0, bytes.Length);
     for(int i=0; i<2*len; i++)
         ms.WriteByte((byte)255);
     ms.SetLength(len);
     ms.Seek(spanPastEnd, SeekOrigin.End);
     for(int i=0; i<bytes.Length; i++)
         ms.WriteByte(bytes[i]);
     ms.Position = bytes.Length;
     byte[] newData = new byte[bytes.Length + spanPastEnd];
     int n = ms.Read(newData, 0, newData.Length);
     if (n != newData.Length) 
     {
         iCountErrors++ ;
         throw new Exception("Hmmm, maybe a bug in the stream.  Asked to read "+newData.Length+", but got back "+n+" bytes.");
     }
     for(int i=0; i<spanPastEnd; i++)
     {
         if (newData[i] != 0)
         {
             iCountErrors++ ;
             throw new Exception(String.Format("New data in the middle of the stream should have been all 0's, but at position {0} I got a wrong byte: {1} [0x{1:x}]!", i+bytes.Length, newData[i]));
         }
     }
     for(int i=0; i<bytes.Length; i++)
     {
         if (newData[i+spanPastEnd] != bytes[i])
         {
             iCountErrors++ ;
             throw new Exception(String.Format("New data at the end of the stream should have been equal to our byte[], but the {0}'th new byte was a wrong byte: {1} [0x{1:x}]!", i, newData[i+spanPastEnd]));
         }
     }
     ms.Flush();
     ms.Close();
     return true;
 }    
开发者ID:ArildF,项目名称:masters,代码行数:44,代码来源:memorystream02.cs

示例11: runTest

 public Boolean runTest()
 {
     Console.Error.WriteLine( s_strTFPath + " " + s_strTFName + " , for " + s_strComponentBeingTested + "  ,Source ver " + s_strDtTmVer );
     int iCountTestcases = 0;
     int iCountErrors    = 0;
     if ( verbose ) Console.WriteLine( "Make sure Flush does not throw in normal case" );
     try
     {
         ++iCountTestcases;
         MemoryStream ms = new MemoryStream();
         ms.Flush();
     }
     catch (Exception ex)
     {
         ++iCountErrors;
         Console.WriteLine( "Err_001b,  Unexpected exception was thrown ex: " + ex.ToString() );
     }
     if ( verbose ) Console.WriteLine( "Make sure Flush does not throw after Close" );
     try
     {
         ++iCountTestcases;
         MemoryStream ms = new MemoryStream();
         ms.Close();
         ms.Flush();
     }
     catch (Exception ex)
     {
         ++iCountErrors;
         Console.WriteLine( "Err_002b,  Unexpected exception was thrown ex: " + ex.ToString() );
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs.   "+ s_strTFPath +" "+ s_strTFName +"  ,iCountTestcases="+ iCountTestcases.ToString() );
         return true;
     }
     else
     {
         Console.WriteLine( "FAiL!   "+ s_strTFPath +" "+ s_strTFName +"  ,iCountErrors="+ iCountErrors.ToString() +" ,BugNums?: "+ s_strActiveBugNums );
         return false;
     }
 }
开发者ID:gbarnett,项目名称:shared-source-cli-2.0,代码行数:41,代码来源:co1808flush.cs

示例12: PrettyPrint

        public static string PrettyPrint(string xml)
        {
            string Result = "";

            MemoryStream MS = new MemoryStream();
            XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
            XmlDocument D = new XmlDocument();

            try {
                // Load the XmlDocument with the XML.
                D.LoadXml(XML);

                W.Formatting = Formatting.Indented;

                // Write the XML into a formatting XmlTextWriter
                D.WriteContentTo(W);
                W.Flush();
                MS.Flush();

                // Have to rewind the MemoryStream in order to read
                // its contents.
                MS.Position = 0;

                // Read MemoryStream contents into a StreamReader.
                StreamReader SR = new StreamReader(MS);

                // Extract the text from the StreamReader.
                string FormattedXML = SR.ReadToEnd();

                Result = FormattedXML;
            }
            catch (XmlException) {
            }

            MS.Close();
            W.Close();

            return Result;
        }
开发者ID:pombredanne,项目名称:tools-12,代码行数:39,代码来源:XMLPrettyPrint.cs

示例13: GetMapImageURL

    /// <summary>
    /// Return http map image URL
    /// </summary>
    /// <returns>http URL of PNG map image </returns>
    public string GetMapImageURL()
    {
        string RetVal = string.Empty;
        string MapFileWPath = string.Empty;
        Map diMap = null;
        string ShareMapFileWPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath + Constants.FolderName.ShareMap, System.Guid.NewGuid() + ".png");
        string AbsoluteTempFile = HttpContext.Current.Request.Url.AbsoluteUri;
        Theme CurrentTheme = null;
        string MissingLegendTitle = string.Empty;
        MemoryStream tStream = new MemoryStream();
        float ActualHeight = 0;
        float Actualwidth = 0;
        bool includeLegend = true;
        string TempFileWPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath + Constants.FolderName.TempCYV, DateTime.Now.Ticks.ToString());

        try
        {
            //step To load map from session/ NewMap/ From preserved file
            diMap = this.GetSessionMapObject();

            ActualHeight = diMap.Height;
            Actualwidth = diMap.Width;

            CurrentTheme = diMap.Themes.GetActiveTheme();

            MissingLegendTitle = CurrentTheme.Legends[CurrentTheme.Legends.Count - 1].Title;
            CurrentTheme.Legends[CurrentTheme.Legends.Count - 1].Title = string.Empty;

            //diMap.DrawMap(TempFileWPath, null);
            if (!Directory.Exists(Path.GetDirectoryName(ShareMapFileWPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(ShareMapFileWPath));
            }

            //diMap.GetCompositeMapImage(Path.GetDirectoryName(ShareMapFileWPath), Path.GetFileNameWithoutExtension(ShareMapFileWPath), "png", Path.GetDirectoryName(ShareMapFileWPath), false, string.Empty, true, true);
            diMap.GetCompositeMapImage(tStream, "png", Path.GetDirectoryName(TempFileWPath), false, string.Empty, includeLegend, true, Actualwidth, ActualHeight);

            this.SaveMemoryStreamIntoFile(tStream, ShareMapFileWPath);
            RetVal = Path.Combine(AbsoluteTempFile.Substring(0, AbsoluteTempFile.LastIndexOf("libraries")), ShareMapFileWPath.Substring(ShareMapFileWPath.LastIndexOf("stock"))).Replace("\\", "/");

        }
        catch (Exception ex)
        {
            //Global.WriteErrorsInLog("From GetMapImageURL ->" + ex.Message);
            RetVal = "false" + Constants.Delimiters.ParamDelimiter + ex.Message;
            Global.CreateExceptionString(ex, null);

        }
        finally
        {
            if (diMap != null)
            {
                diMap.Height = ActualHeight;
                diMap.Width = Actualwidth;
            }

            if (tStream != null)
            {
                tStream.Flush();
                tStream.Close();
            }

            if (CurrentTheme != null || CurrentTheme.Legends != null)
            {
                //reset legend setting after export
                CurrentTheme.Legends[CurrentTheme.Legends.Count - 1].Title = MissingLegendTitle;
            }
        }

        return RetVal;
    }
开发者ID:SDRC-India,项目名称:sdrcdevinfo,代码行数:75,代码来源:MapCallback.cs

示例14: combustibleIndividual


//.........这里部分代码省略.........
                  tablaHist.Style = EstiloTabla;
                  tablaHist.Borders.Color = ColorBorderTabla;
                  tablaHist.Borders.Width = BorderWidth;
                  tablaHist.Borders.Left.Width = LeftWidth;
                  tablaHist.Borders.Right.Width = RightWidth;
                  tablaHist.Rows.LeftIndent = LeftIndent;

                  for (int i = 0; i < MedidasCombuHist.Length; i++)
                      tablaHist.AddColumn(MedidasCombuHist[i]);

                  Row rowHist = tablaHist.AddRow();
                  rowHist.HeadingFormat = true;
                  rowHist.Format.Alignment = AlineamientoTableHead;
                  rowHist.Format.Font.Bold = true;
                  rowHist.Shading.Color = ColorFondoTableHead;

                  rowHist.Cells[0].AddParagraph(fechaStr);
                  rowHist.Cells[1].AddParagraph(speedStr);
                  rowHist.Cells[2].AddParagraph(direccion);
                  rowHist.Cells[3].AddParagraph(eventoStr);
                  rowHist.Cells[4].AddParagraph(volStr + " (" + volUnit + ")");

                  int counterHist = 0;
                  dynamic dataArrayHist = fuelReporObj.dataHist;
                  foreach (var eventObj in dataArrayHist)
                  {
                      var date = eventObj.date;
                      var vel = eventObj.speed;
                      var address = eventObj.address;
                      var eventHist = eventObj.evento;
                      var volume = eventObj.volume;
                      var city = eventObj.city;

                      rowHist = tablaHist.AddRow();
                      if (counterHist % 2 == 0)
                          rowHist.Shading.Color = ColorFondoRow;

                      rowHist.Cells[0].AddParagraph((string)date);
                      rowHist.Cells[1].AddParagraph((string)vel);
                      rowHist.Cells[2].AddParagraph((string)address + " " + (string)city);
                      rowHist.Cells[3].AddParagraph((string)eventHist);
                      rowHist.Cells[4].AddParagraph((string)volume);
                      counterHist++;
                  }
              }
          }
        /******************** ESTA SECCION ES PARA AGREGAR TABLAS DE GRUPAL ************/
        else
        {

            dynamic dataArrayGroup = fuelReporObj.groupData;
            dynamic dataArrayInit = fuelReporObj.initialFuelData;
            dynamic dataArrayLoad = fuelReporObj.fuelLoadData;
            dynamic dataArrayDis = fuelReporObj.fuelDischargeData;
            dynamic dataArrayiddle = fuelReporObj.idleData;
            dynamic dataArrayConsumed = fuelReporObj.consumedData;
            dynamic dataArrayCurrent = fuelReporObj.currentFuelData;

            string unidadStr = unitStr  ;
            string volumenStr = volStr + volParStr;
            string costoStr = costStr + currencyParStr;
            string velMaxStr = velMaxHead + velStr;
            string tMovStr = tiempoMovStr  ;
            string tMuertoStr = tiempoMuertoStr;
            string rendBrutoStr = perfBruteHead + performanceStr;
            string rendEfectivo = perfEfecHead + performanceStr;
            string cantStr = cantidadStr;
            string time = timeStr;

            string[] groupHeaders = new[] { unidadStr, velMaxStr, tMovStr, tMuertoStr, rendBrutoStr, rendEfectivo };
            string[] initalHeaders = new[] { unidadStr, volumenStr, costoStr };
            string[] fuelChargeHeader = new[] { unidadStr, cantStr, volumenStr, costoStr };
            string[] ralentiHeader = new[] { unidadStr, time, volumenStr, costoStr };
            string[] consumedHeader = new[] { unidadStr, time, volumenStr, costoStr };

            createTable(section, behFuelTable, groupHeaders, dataArrayGroup, "comportamiento");
            createTable(section, intiTable, initalHeaders, dataArrayInit, "initial");
            createTable(section, finalTable, initalHeaders, dataArrayCurrent, "final");
            createTable(section, chargesTable, fuelChargeHeader, dataArrayLoad, "cargas");
            createTable(section, drainTable, fuelChargeHeader, dataArrayDis, "descargas");
            createTable(section, idleTable, ralentiHeader, dataArrayiddle, "ralenti");
            createTable(section, consumed, consumedHeader, dataArrayConsumed, "consumido");

        }

           /**** Este es el final al terminar de hacer el PDF ***/
           PdfDocumentRenderer renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
           renderer.Document = document;
           renderer.RenderDocument();

           using (MemoryStream ms = new MemoryStream())
           {
           renderer.Save(ms, false);
           byte[] buffer = new byte[ms.Length];
           ms.Seek(0, SeekOrigin.Begin);
           ms.Flush();
           ms.Read(buffer, 0, (int)ms.Length);
           return ms.ToArray();
           }
    }
开发者ID:SandyMG,项目名称:initial-chumaster,代码行数:101,代码来源:ReportesPdf.cs

示例15: Save

    public void Save()
    {
        /*for (var loopRow = Worksheet.FirstRowNum; loopRow <= Worksheet.LastRowNum; loopRow++)
        {
            var row = Worksheet.GetRow(loopRow);
            bool emptyRow = true;
            foreach (var cell in row.Cells)
            {
                if (!string.IsNullOrEmpty(cell.ToString()))
                    emptyRow = false;
            }
            if (emptyRow)
                Worksheet.RemoveRow(row);
        }*/
        //try
        {
            using (var memStream = new MemoryStream())
            {
                Workbook.Write(memStream);
                memStream.Flush();
                memStream.Position = 0;

                using (var fileStream = new FileStream(Path, FileMode.Create, FileAccess.Write))
                {
                    var data = memStream.ToArray();
                    fileStream.Write(data, 0, data.Length);
                    fileStream.Flush();
                }
            }

        }
        //catch (Exception e)
        //{
        //    CDebug.LogError(e.Message);
        //    CDebug.LogError("是否打开了Excel表?");
        //}

    }
开发者ID:henry-yuxi,项目名称:CosmosEngine,代码行数:38,代码来源:CExcelFile.cs


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