Write() public méthode

public Write ( byte array, int offset, int count ) : void
array byte
offset int
count int
Résultat void
        public override void ShowUsage()
        {
            //BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。
            //为什么要封装其他流类,这么做的意义是什么?按照微软的话说主要是减少某些流直接操作存储设备的时间。
            //对于一些流来说直接向磁盘中存储数据这种做法的效率并不高,用BufferedStream包装过的流,先在内存中进行统一的处理再向磁盘中写入数据,也会提高写入的效率。

            Console.WriteLine("BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。");
            FileStream fileStream1 = File.Open(@"C:\NewText.txt", FileMode.OpenOrCreate, FileAccess.Read);  //读取文件流
            FileStream fileStream2 = File.Open(@"C:\Text2.txt", FileMode.OpenOrCreate, FileAccess.Write);   //写入文件流

            byte[] array4 = new byte[4096];

            BufferedStream bufferedInput = new BufferedStream(fileStream1);         //封装文件流
            BufferedStream bufferedOutput = new BufferedStream(fileStream2);        //封装文件流

            int byteRead = bufferedInput.Read(array4, 0, array4.Length);
            bufferedOutput.Write(array4, 0, array4.Length);

            //= bufferedInput.Read(array4, 0, 4096);
            while (byteRead > 0)                                                    //读取到了数据
            {
                bufferedOutput.Write(array4, 0, byteRead);
                Console.WriteLine(byteRead);
                break;
            };
            bufferedInput.Close();
            bufferedOutput.Close();
            fileStream1.Close();
            fileStream2.Close();
            Console.ReadKey();
        }
Exemple #2
0
    /* add a jpeg frame to an AVI file */
    public void avi_add(u8[] buf, uint size)
    {
        uint osize = size;

        Console.WriteLine(DateTime.Now.Millisecond + " avi frame");
        db_head db = new db_head {
            db = "00dc".ToCharArray(), size = size
        };

        fd.Write(StructureToByteArray(db), 0, Marshal.SizeOf(db));
        fd.Write(buf, 0, (int)size);
        if (size % 2 == 1)
        {
            size++;
            fd.Seek(1, SeekOrigin.Current);
        }
        nframes++;
        totalsize += size;

        if (((DateTime.Now - start).TotalSeconds * targetfps) > nframes)
        {
            avi_add(buf, osize);
            Console.WriteLine("Extra frame");
        }
    }
Exemple #3
0
        public void putFile()
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("这个请求是一个普通文件");
            Console.ResetColor();

            outputStream.WriteLine("HTTP/1.0 200 OK");
            outputStream.WriteLine("Content-Type: application/octet-stream");
            outputStream.WriteLine("Content-Disposition: attachment");
            outputStream.WriteLine("Connection: close");
            outputStream.WriteLine("");
            outputStream.Flush();

            FileStream stream = new FileStream(http_url_ondisk, FileMode.Open, FileAccess.Read);

            try
            {
                byte[] buff2 = new byte[1024];
                int    count = 0;
                while ((count = stream.Read(buff2, 0, 1024)) != 0)
                {
                    outputByteStream.Write(buff2, 0, count);
                }
                outputByteStream.Flush();
                outputByteStream.Close();
                stream.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("停止传输文件");
                stream.Close();
                outputByteStream.Close();
            }
        }
        public void BadXmlTests()
        {
            try {
            EncodeHelper.Deserialize("<garbage />", typeof(System.Object));
            Assert.Fail("You should not have been able to deserialize this preceding xml");
              }
              catch {
              }

              MemoryStream ms = new MemoryStream();
              using (StreamWriter sw = new StreamWriter(ms)) {
            sw.Write("<garbage />");
            sw.Flush();
            object test = EncodeHelper.Deserialize(ms);
            Assert.AreEqual(null, test);
              }

              try {
            //Test the Deserialize method that builds an error message.
            ms = new MemoryStream();
            using (BufferedStream sw = new BufferedStream(ms)) {
              sw.Write(Encoding.UTF8.GetPreamble(), 0, 3);
              byte[] msg = System.Text.Encoding.UTF8.GetBytes("<garbage>");
              sw.Write(msg, 0, msg.Length);
              sw.Flush();
              ms.Position = 0;
              object test = EncodeHelper.Deserialize(ms);
              Assert.AreEqual(null, test);
            }
              }
              catch (Exception ex) {
            if (ex.Message.IndexOf("Couldn't parse XML") == -1)
              Assert.Fail("We should have failed for a bad xml file.");
              }
        }
 public static void Write_Arguments()
 {
     using (BufferedStream stream = new BufferedStream(new MemoryStream()))
     {
         byte[] array = new byte[10];
         Assert.Throws<ArgumentNullException>("array", () => stream.Write(null, 1, 1));
         Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(array, -1, 1));
         Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(array, 1, -1));
         Assert.Throws<ArgumentException>(() => stream.Write(array, 9, 2));
     }
 }
Exemple #6
0
        public void Execute()
        {
            MemoryStream buffer = new MemoryStream();
            formatter.Serialize(buffer, message);

            byte[] bytes = buffer.ToArray();
            byte[] size = BitConverter.GetBytes((int)buffer.Length);

            Stream stream = new BufferedStream(client.GetStream());
            stream.Write(size, 0, size.Length);
            stream.Write(bytes, 0, bytes.Length);
            stream.Flush();
        }
        internal static void DownloadContent(string url, string path, bool static_content)
        {
            if(File.Exists(path)) {
                DateTime last_updated_time = File.GetLastWriteTime (path);
                if(static_content || DateTime.Now - last_updated_time < CACHE_TIME) {
                    return;
                }
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = "Banshee Recommendation Plugin";
            request.KeepAlive = false;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();

            FileStream file_stream = File.OpenWrite(path);
            BufferedStream buffered_stream = new BufferedStream(file_stream);

            byte [] buffer = new byte[8192];
            int read;

            while(true) {
                read = stream.Read(buffer, 0, buffer.Length);
                if(read <= 0) {
                    break;
                }

                buffered_stream.Write(buffer, 0, read);
            }

            buffered_stream.Close();
            response.Close();
        }
        public void BufferColumnStream()
        {
            var data = new byte[1024];

            var memoryStream = new MemoryStream();

            Api.JetBeginTransaction(this.sesid);
            Api.JetPrepareUpdate(this.sesid, this.tableid, JET_prep.Insert);
            using (var stream = new BufferedStream(new ColumnStream(this.sesid, this.tableid, this.columnidLongText), SystemParameters.LVChunkSizeMost))
            {
                for (int i = 0; i < 10; ++i)
                {
                    stream.Write(data, 0, data.Length);
                    memoryStream.Write(data, 0, data.Length);
                }
            }

            this.UpdateAndGotoBookmark();
            Api.JetCommitTransaction(this.sesid, CommitTransactionGrbit.LazyFlush);

            var hasher = new SHA512Managed();
            memoryStream.Position = 0;
            var expected = hasher.ComputeHash(memoryStream);

            using (var stream = new BufferedStream(new ColumnStream(this.sesid, this.tableid, this.columnidLongText), SystemParameters.LVChunkSizeMost))
            {
                var actual = hasher.ComputeHash(stream);
                CollectionAssert.AreEqual(expected, actual);
            }
        }
Exemple #9
0
 private void button3_Click(object sender, EventArgs e)
 {
     try
     {
         string str1 = textBox1.Text;
         string str2 = textBox2.Text + "\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - textBox1.Text.LastIndexOf("\\") - 1);
         Stream myStream1, myStream2;
         BufferedStream myBStream1, myBStream2;
         byte[] myByte = new byte[1024];
         int i;
         myStream1 = File.OpenRead(str1);
         myStream2 = File.OpenWrite(str2);
         myBStream1 = new BufferedStream(myStream1);
         myBStream2 = new BufferedStream(myStream2);
         i = myBStream1.Read(myByte, 0, 1024);
         while (i > 0)
         {
             myBStream2.Write(myByte, 0, i);
             i = myBStream1.Read(myByte, 0, 1024);
         }
         myBStream2.Flush();
         myStream1.Close();
         myBStream2.Close();
         MessageBox.Show("文件复制完成");
     }
     catch(Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemple #10
0
        /* Unzips dirName + ".zip" --> dirName, removing dirName
         * first */
        public virtual void  Unzip(System.String zipName, System.String destDirName)
        {
#if SHARP_ZIP_LIB
            // get zip input stream
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zipFile;
            zipFile = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(System.IO.File.OpenRead(zipName + ".zip"));

            // get dest directory name
            System.String      dirName = FullDir(destDirName);
            System.IO.FileInfo fileDir = new System.IO.FileInfo(dirName);

            // clean up old directory (if there) and create new directory
            RmDir(fileDir.FullName);
            System.IO.Directory.CreateDirectory(fileDir.FullName);

            // copy file entries from zip stream to directory
            ICSharpCode.SharpZipLib.Zip.ZipEntry entry;
            while ((entry = zipFile.GetNextEntry()) != null)
            {
                System.IO.Stream streamout = new System.IO.BufferedStream(new System.IO.FileStream(new System.IO.FileInfo(System.IO.Path.Combine(fileDir.FullName, entry.Name)).FullName, System.IO.FileMode.Create));
                byte[]           buffer    = new byte[8192];
                int len;
                while ((len = zipFile.Read(buffer, 0, buffer.Length)) > 0)
                {
                    streamout.Write(buffer, 0, len);
                }

                streamout.Close();
            }

            zipFile.Close();
#else
            Assert.Fail("Needs integration with SharpZipLib");
#endif
        }
Exemple #11
0
        public static IEnumerable<byte> GetCompressedFileBytes(string file)
        {
            if (CheckSignature(file, 4, ZipSig) || CheckSignature(file, 3, GZipSig))
            {
                Console.WriteLine($"{file} seems to be a compressed file");

                return GetFileBytes(file);
            }

            // TODO: add blacklist for known compressed formats
            byte[] bytes = GetFileBytes(file).ToArray();
            using (MemoryStream mem = new MemoryStream())
            {
                using (BufferedStream buffer = new BufferedStream(new GZipStream(mem, CompressionMode.Compress)))
                    buffer.Write(bytes, 0, bytes.Length);

                byte[] result = mem.ToArray();
                Console.WriteLine($"{bytes.Length} -> {result.Length}");

                if (bytes.Length < result.Length)
                    return bytes;

                return result;
            }
        }
Exemple #12
0
        public void Stream2Test()
        {
            var ms = new BufferedStream(new MemoryStream());
            Console.WriteLine(ms.CanWrite);
            Console.WriteLine(ms.CanRead);
            ms.Write(new byte[3] { 1, 2, 3 }, 0, 3);
            ms.Flush();

            var bys = new byte[10];
            var len = ms.Read(bys, 0, 10);
            Console.WriteLine(len + "->" + bys[0]);
        }
Exemple #13
0
        public static byte[] Compress(byte[] inputData)
        {
            if (inputData == null)
                throw new ArgumentNullException("inputData");

            using (var compressIntoMs = MiNetServer.MemoryStreamManager.GetStream())
            {
                using (var gzs = new BufferedStream(new GZipStream(compressIntoMs, CompressionMode.Compress), 2*4096))
                {
                    gzs.Write(inputData, 0, inputData.Length);
                }
                return compressIntoMs.ToArray();
            }
        }
        /// <summary>
        /// Work around a 64Mb limit when writing streams to files.
        /// <seealso cref="http://groups.google.co.uk/group/microsoft.public.dotnet.framework/browse_thread/thread/ba3582b0a6e45517/03e8d3c8718a9c44"/>
        /// </summary>
        public static void WriteMemoryStreamToFile(string filename, MemoryStream memory)
        {
            //// old code:
            //using (Stream
            //    file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite),
            //    fileBuffer = new BufferedStream(file)
            //)
            //{
            //    byte[] memoryBuffer = memory.GetBuffer();
            //    int memoryLength = (int)memory.Length;
            //    fileBuffer.Write(memoryBuffer, 0, memoryLength); //##jpl: drawback: works only up to 2 gigabyte!
            //    fileBuffer.Close();
            //    file.Close();
            //}

            using (System.IO.Stream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                using (Stream buffer = new System.IO.BufferedStream(file))
                {
                    byte[] memoryBuffer = memory.GetBuffer();
                    long   memoryLength = memory.Length;
                    int    index        = 0;
                    // writing everything at once fails for writing memory streams larger than 64 megabyte
                    // to a file stream on the network
                    //buffer.Write(memoryBuffer, 0, memoryLength);
                    // so we introduce a temporary buffer
                    const int copyBufferSize = 65536;
                    byte[]    copyBuffer     = new byte[copyBufferSize];
                    while (memoryLength > 0)
                    {
                        int actualLength;
                        if (memoryLength > copyBufferSize)
                        {
                            actualLength = copyBufferSize;
                        }
                        else
                        {
                            actualLength = (int)memoryLength; //jpl: this cast is valid, as now memoryLength <= copyBufferSize
                        }
                        Array.Copy(memoryBuffer, index, copyBuffer, 0, actualLength);
                        buffer.Write(copyBuffer, 0, actualLength);
                        memoryLength = memoryLength - actualLength;
                        index        = index + actualLength;
                    }
                    buffer.Flush();
                    buffer.Close();
                }
            }
        }
Exemple #15
0
        private static int BUFFER_SIZE = 8 * 1024 * 1024; //8MB //64kB

        public static byte[] Compress(byte[] inputData)
        {
            if (inputData == null)
                throw new ArgumentNullException("inputData must be non-null");

            using (var compressIntoMs = new MemoryStream())
            {
                using (var gzs = new BufferedStream(new GZipStream(compressIntoMs,
                 CompressionMode.Compress), BUFFER_SIZE))
                {
                    gzs.Write(inputData, 0, inputData.Length);
                }
                return compressIntoMs.ToArray();
            }
        }
        /// <summary>
        /// 테스트용 임시 파일을 생성한다.
        /// </summary>
        public FileInfo CreateTestFile(string filepath, long size) {
            var fi = new FileInfo(filepath);

            var buffer = new byte[BufferSize];

            ArrayTool.GetRandomBytes(buffer);

            using(var bs = new BufferedStream(fi.OpenWrite())) {
                long writeCount = 0;
                do {
                    bs.Write(buffer, 0, BufferSize);
                    writeCount += BufferSize;
                } while(size > writeCount);

                bs.Flush();
            }

            return fi;
        }
        public void getQRCode()
        {
            string url_login = "******";
            httpClient.MaxResponseContentBufferSize = 256000;
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
            HttpResponseMessage response = httpClient.GetAsync(new Uri(url_login)).Result;
            HttpRequestMessage request = response.RequestMessage;
            if (response.StatusCode != HttpStatusCode.OK)
            {
                //异常,
            }
            SetCookies = response.Headers.GetValues("Set-Cookie");

            FileStream fs = new FileStream(dir + "code.png", FileMode.Create);       
            BufferedStream sw = new BufferedStream(fs,1024);
            byte[] imgdata = null;
            imgdata = response.Content.ReadAsByteArrayAsync().Result;
            //var data  =  response.Content.ReadAsByteArrayAsync().Result;
            sw.Write(imgdata,0, imgdata.Length);
            sw.Close();
            fs.Close();
        }
        public static void CreatePTableFile(string filename, long ptableSize, int indexEntrySize, int cacheDepth = 16)
        {
            Ensure.NotNullOrEmpty(filename, "filename");
            Ensure.Nonnegative(cacheDepth, "cacheDepth");

            var sw = Stopwatch.StartNew();
            var tableId = Guid.NewGuid();
            using (var fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None,
                                           DefaultSequentialBufferSize, FileOptions.SequentialScan))
            {
                fs.SetLength((long)ptableSize);
                fs.Seek(0, SeekOrigin.Begin);

                var recordCount = (long)((ptableSize - PTableHeader.Size - PTable.MD5Size) / (long)indexEntrySize);
                using (var md5 = MD5.Create())
                using (var cs = new CryptoStream(fs, md5, CryptoStreamMode.Write))
                using (var bs = new BufferedStream(cs, DefaultSequentialBufferSize))
                {
                    // WRITE HEADER
                    var headerBytes = new PTableHeader(Version).AsByteArray();
                    cs.Write(headerBytes, 0, headerBytes.Length);

                    // WRITE INDEX ENTRIES
                    var buffer = new byte[indexEntrySize];
                    for (long i = 0; i < recordCount; i++)
                    {
                        bs.Write(buffer, 0, indexEntrySize);
                    }
                    bs.Flush();
                    cs.FlushFinalBlock();

                    // WRITE MD5
                    var hash = md5.Hash;
                    fs.Write(hash, 0, hash.Length);
                }
            }
            Console.WriteLine("Created PTable File[{0}, size of {1}] in {2}.", tableId, ptableSize, sw.Elapsed);
        }
        void Process(string inPath, string outPath)
        {
            var buffer = new byte[BufferSize];
            var generator = BuildGenerator();

            using (var reader = new BufferedStream(new FileStream(inPath, FileMode.Open)))
            using (var writer = new BufferedStream(new FileStream(outPath, FileMode.Create)))
            {
                while (true)
                {
                    var read = reader.Read(buffer, 0, BufferSize);
                    if (read == 0)
                    {
                        break;
                    }
                    for (var i = 0; i < read; i++)
                    {
                        generator.MoveNext();
                        buffer[i] = (byte) (buffer[i] ^ generator.Current);
                    }
                    writer.Write(buffer, 0, read);
                }
            }
        }
        /// <summary>
        /// Reades all data from the specified stream and writes it to source stream. Period handlign and period terminator is added as required.
        /// </summary>
        /// <param name="stream">Stream which data to write to source stream.</param>
        /// <param name="maxSize">Maximum muber of bytes to read from <b>stream</b> and write source stream.</param>
        /// <returns>Returns number of bytes written to source stream. Note this value differs from 
        /// <b>stream</b> readed bytes count because of period handling and period terminator.
        /// </returns>
        /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception>
        /// <exception cref="InvalidOperationException">Raised when there already is pending write operation.</exception>
        /// <exception cref="LineSizeExceededException">Raised when <b>stream</b> contains line with bigger line size than allowed.</exception>
        /// <exception cref="DataSizeExceededException">Raised when <b>stream</b> has more data than <b>maxSize</b> allows..</exception>
        public int WritePeriodTerminated(Stream stream,int maxSize)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            lock(this){
                if(m_IsWriteActive){
                    throw new InvalidOperationException("There is pending write operation, multiple write operations not allowed !");
                }
                m_IsWriteActive = true;
            }

            try{
                BufferedStream bufferedStoreStream = new BufferedStream(m_pStream,32000);
                StreamHelper   reader              = new StreamHelper(stream);
                int            totalWrittenCount   = 0;
                int            readedCount         = 0;
                int            rawReadedCount      = 0;
                while(true){
                    // Read data block.
                    readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.ThrowException,out rawReadedCount,false);

                    // We reached end of stream, no more data.
                    if(readedCount == 0){
                        break;
                    }

                    // Maximum allowed data size exceeded.
                    if((totalWrittenCount + rawReadedCount) > maxSize){
                        throw new DataSizeExceededException();
                    }

                    // If line starts with period(.), additional period is added.
                    if(m_pLineBuffer[0] == '.'){
                        bufferedStoreStream.WriteByte((byte)'.');
                        totalWrittenCount++;
                    }

                    // Write readed line to buffered stream.
                    bufferedStoreStream.Write(m_pLineBuffer,0,readedCount);
                    bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length);
                    totalWrittenCount += (readedCount + m_LineBreak.Length);
                }

                // Write terminator ".<CRLF>". We have start <CRLF> already in stream.
                bufferedStoreStream.Write(new byte[]{(byte)'.',(byte)'\r',(byte)'\n'},0,3);
                bufferedStoreStream.Flush();
                m_pStream.Flush();

                // Log
                if(this.Logger != null){
                    this.Logger.AddWrite(totalWrittenCount,null);
                }

                return totalWrittenCount;
            }
            finally{
                m_IsWriteActive = false;
            }
        }
Exemple #21
0
        private Response TcpRequest(Request request)
        {
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();

            byte[] responseMessage = new byte[512];

            for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++)
            {
                for (int intDnsServer = 0; intDnsServer < m_DnsServers.Count; intDnsServer++)
                {
                    using( TcpClient tcpClient = new TcpClient() )
                    {
                        tcpClient.ReceiveTimeout = m_Timeout * 1000;

                        try
                        {
                            IAsyncResult result = tcpClient.BeginConnect(m_DnsServers[intDnsServer].Address, m_DnsServers[intDnsServer].Port, null, null);

                            bool success = result.AsyncWaitHandle.WaitOne(m_Timeout*1000, true);

                            if (!success || !tcpClient.Connected)
                            {
                                Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                                continue;
                            }

                            BufferedStream bs = new BufferedStream(tcpClient.GetStream());

                            byte[] data = request.Data;
                            bs.WriteByte((byte)((data.Length >> 8) & 0xff));
                            bs.WriteByte((byte)(data.Length & 0xff));
                            bs.Write(data, 0, data.Length);
                            bs.Flush();

                            Response TransferResponse = new Response();
                            int intSoa = 0;
                            int intMessageSize = 0;

                            //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");

                            while (true)
                            {
                                int intLength = bs.ReadByte() << 8 | bs.ReadByte();
                                if (intLength <= 0)
                                {
                                    Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                                    throw new SocketException(); // next try
                                }

                                intMessageSize += intLength;

                                data = new byte[intLength];
                                bs.Read(data, 0, intLength);
                                Response response = new Response(m_DnsServers[intDnsServer], data);

                                //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");

                                if (response.header.RCODE != RCode.NoError)
                                    return response;

                                if (response.Questions[0].QType != QType.AXFR)
                                {
                                    AddToCache(response);
                                    return response;
                                }

                                // Zone transfer!!

                                if(TransferResponse.Questions.Count==0)
                                    TransferResponse.Questions.AddRange(response.Questions);
                                TransferResponse.Answers.AddRange(response.Answers);
                                TransferResponse.Authorities.AddRange(response.Authorities);
                                TransferResponse.Additionals.AddRange(response.Additionals);

                                if (response.Answers[0].Type == Type.SOA)
                                        intSoa++;

                                if (intSoa == 2)
                                {
                                    TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count;
                                    TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count;
                                    TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count;
                                    TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count;
                                    TransferResponse.MessageSize = intMessageSize;
                                    return TransferResponse;
                                }
                            }
                        } // try
                        catch (SocketException)
                        {
                            continue; // next try
                        }
                        finally
                        {
                            m_Unique++;
                        }
                    }
                }
            }
            Response responseTimeout = new Response();
            responseTimeout.Error = "Timeout Error";
            return responseTimeout;
        }
Exemple #22
0
        /*
        Map File Format
        
        The first 65536 bytes of the map file is the graphical portion of the map.
        The next 65536 bytes appears to be the map that is used for path finding.
        
        The next 4 bytes is the number of markers on the map.
        
        The markers than follow here. If there are no markers than nothing
        is beyond the marker count bytes.
        
        
        Marker Format
        
        The first byte appears to be the x position
        The second byte appears to be the map tile it is in on the x axis
        Two blank bytes
        
        The next byte appears to the y position
        The next byte appears to be the map tile it is in on the y axis
        Two blank bytes
        
        The next 4 bytes are the image id of the image
        
        The next 2 bytes are the size of the string that fallows
        The string of text for the marker
        */


        /// <summary>
        /// Merges tibia maps together. The input files are only read from.
        /// </summary>
        /// <param name="serverType">The type of server (Real or OT)</param>
        /// <param name="outputDirectory">The directory where the merged maps will go.</param>
        /// <param name="inputDirectories">A list of directories that contain the tibia maps to be merged together.</param>
        /// <returns>
        /// Returns true if successful. If it returns false the files in the output
        /// directory may be corrupted and incorrect.
        /// </returns>
        public static bool Merge(Constants.ServerType serverType, string outputDirectory, params string[] inputDirectories)
        {
            if (inputDirectories.Length < 1)
                return false;

            string mask = null;

            if (serverType == Pokemon.Constants.ServerType.Real)
                mask = "1??1????.map";
            else
                mask = "0??0????.map";

            string[] files = Directory.GetFiles(inputDirectories[0], mask);

            try
            {
                foreach (string file in files)
                {
                    File.Copy(file, outputDirectory + "/" + Path.GetFileName(file), true);
                }
            }
            catch
            {
                return false;
            }

            for (int i = 1; i < inputDirectories.Length; ++i)
            {
                files = Directory.GetFiles(inputDirectories[i]);

                foreach (string file in files)
                {
                    if (!File.Exists(outputDirectory + "/" + Path.GetFileName(file)))
                    {
                        try
                        {
                            File.Copy(file, outputDirectory + "/" + Path.GetFileName(file));
                        }
                        catch
                        {
                            return false;
                        }
                    }
                    else
                    {
                        FileStream sourcefile = null;
                        FileStream inputfile = null;
                        BufferedStream sourcebuffered = null;
                        BufferedStream inputbuffered = null;

                        try
                        {
                            //Setup the streams and buffers
                            sourcefile = new FileStream(outputDirectory + "/" + Path.GetFileName(file), FileMode.Open);
                            inputfile = new FileStream(file, FileMode.Open);
                            sourcebuffered = new BufferedStream(sourcefile);
                            inputbuffered = new BufferedStream(inputfile);


                            //Read and write the graphical data
                            byte[] source = new byte[65536];
                            sourcebuffered.Read(source, 0, 65536);

                            byte[] input = new byte[65536];
                            inputbuffered.Read(input, 0, 65536);

                            Compare(source, input, 0, 65536);

                            sourcebuffered.Seek(0, SeekOrigin.Begin);
                            sourcebuffered.Write(source, 0, 65536);


                            //Read and write the pathfinding data
                            sourcebuffered.Seek(65536, SeekOrigin.Begin);
                            inputbuffered.Seek(65536, SeekOrigin.Begin);

                            sourcebuffered.Read(source, 0, 65536);
                            inputbuffered.Read(input, 0, 65536);

                            Compare(source, input, 0xfa, 65536);

                            sourcebuffered.Seek(65536, SeekOrigin.Begin);
                            sourcebuffered.Write(source, 0, 65536);


                            //Read and write the marker data
                            sourcebuffered.Seek(131072, SeekOrigin.Begin);
                            byte[] sourcemarkercountbytes = new byte[4];
                            sourcebuffered.Read(sourcemarkercountbytes, 0, 4);
                            int sourcemarkercount = BitConverter.ToInt32(sourcemarkercountbytes, 0);

                            inputbuffered.Seek(131072, SeekOrigin.Begin);
                            byte[] inputmarkercountbytes = new byte[4];
                            inputbuffered.Read(inputmarkercountbytes, 0, 4);
                            int inputmarkercount = BitConverter.ToInt32(inputmarkercountbytes, 0);

                            List<Marker> sourcemarkers = new List<Marker>();

                            for (int r = 0; r < sourcemarkercount; ++r)
                            {
                                byte[] data = new byte[12];
                                sourcebuffered.Read(data, 0, 12);

                                byte[] stringlength = new byte[2];
                                sourcebuffered.Read(stringlength, 0, 2);
                                int len = BitConverter.ToUInt16(stringlength, 0);

                                byte[] str = new byte[len];
                                sourcebuffered.Read(str, 0, len);
                                sourcebuffered.Seek(len, SeekOrigin.Current);

                                Marker marker = new Marker(data, stringlength, str);
                                sourcemarkers.Add(marker);
                            }

                            for (int r = 0; r < inputmarkercount; ++r)
                            {
                                byte[] data = new byte[12];
                                inputbuffered.Read(data, 0, 12);

                                byte[] stringlength = new byte[2];
                                inputbuffered.Read(stringlength, 0, 2);
                                int len = BitConverter.ToUInt16(stringlength, 0);

                                byte[] str = new byte[len];
                                inputbuffered.Read(str, 0, len);
                                inputbuffered.Seek(len, SeekOrigin.Current);

                                Marker marker = new Marker(data, stringlength, str);

                                //Make sure we arn't copying a marker that already exists
                                if (!sourcemarkers.Contains(marker))
                                {
                                    sourcemarkercount++;

                                    byte[] write = marker.GetBytes();
                                    sourcebuffered.SetLength(sourcebuffered.Length + write.Length);
                                    sourcebuffered.Seek(-write.Length, SeekOrigin.End);
                                    sourcebuffered.Write(write, 0, write.Length);
                                }
                            }

                            sourcebuffered.Seek(131072, SeekOrigin.Begin);
                            sourcemarkercountbytes = BitConverter.GetBytes(sourcemarkercount);
                            sourcebuffered.Write(sourcemarkercountbytes, 0, 4);
                        }
                        catch
                        {
                            return false;
                        }
                        finally
                        {
                            if (sourcebuffered != null)
                                sourcebuffered.Close();

                            if (inputbuffered != null)
                                inputbuffered.Close();

                            if (sourcefile != null)
                                sourcefile.Close();

                            if (inputfile != null)
                                inputfile.Close();
                        }
                    }
                }
            }

            return true;
        }
Exemple #23
0
    /* add a jpeg frame to an AVI file */
    public void avi_add(u8[] buf, uint size)
    {
        Console.WriteLine(DateTime.Now.Millisecond + "avi frame");
        db_head db = new db_head {
            db = "00dc".ToCharArray(), size = size
        };

        fd.Write(StructureToByteArray(db), 0, Marshal.SizeOf(db));
        fd.Write(buf, 0, (int)size);
        if (size % 2 == 1)
        {
            size++;
            fd.Seek(1, SeekOrigin.Current);
        }
        nframes++;
        totalsize += size;
        lista_tams.Add(size);
        if (size > max_buff_size)
        {
            max_buff_size = size;
        }
    }
Exemple #24
0
        public void DecompressFS(string path)
        {
            FileStream fsIn = new FileStream(path + ".gz", FileMode.Open, FileAccess.Read);
            BufferedStream bsIn = new BufferedStream(fsIn);
            GZipStream gzipStream = new GZipStream(bsIn, CompressionMode.Decompress);

            FileStream fsOut = new FileStream(path, FileMode.Create, FileAccess.Write);
            BufferedStream bsOut = new BufferedStream(fsOut);

            byte[] buffer = new byte[8192];
            int count;

            while ((count = gzipStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                bsOut.Write(buffer, 0, count);
            }

            bsOut.Close();
            fsOut.Close();

            gzipStream.Close();
            bsIn.Close();
            fsIn.Close();
        }
		/// <summary>
		/// Write an entry to the archive. This method will call the putNextEntry
		/// and then write the contents of the entry, and finally call closeEntry()()
		/// for entries that are files. For directories, it will call putNextEntry(),
		/// and then, if the recurse flag is true, process each entry that is a
		/// child of the directory.
		/// </summary>
		/// <param name="entry">
		/// The TarEntry representing the entry to write to the archive.
		/// </param>
		/// <param name="recurse">
		/// If true, process the children of directory entries.
		/// </param>
		public void WriteEntry(TarEntry entry, bool recurse)
		{
			bool asciiTrans = false;
			
			string tempFileName = null;
			string eFile        = entry.File;
			
			// Work on a copy of the entry so we can manipulate it.
			// Note that we must distinguish how the entry was constructed.
			//
			if (eFile == null || eFile.Length == 0) {
				entry = TarEntry.CreateTarEntry(entry.Name);
			} 
         else {
				//
				// The user may have explicitly set the entry's name to
				// something other than the file's path, so we must save
				// and restore it. This should work even when the name
				// was set from the File's name.
				//
				string saveName = entry.Name;
				entry = TarEntry.CreateEntryFromFile(eFile);
				entry.Name = saveName;
			}
			
			if (this.verbose) {
				OnProgressMessageEvent(entry, null);
			}
			
			if (this.asciiTranslate && !entry.IsDirectory) {
				asciiTrans = !IsBinary(eFile);

// original java source :
//			    	MimeType mime = null;
//			    	string contentType = null;
//	
//			    	try {
//			    		contentType = FileTypeMap.getDefaultFileTypeMap(). getContentType( eFile );
//			    		
//			    		mime = new MimeType( contentType );
//			    		
//			    		if ( mime.getPrimaryType().
//			    		    equalsIgnoreCase( "text" ) )
//			    		    {
//			    		    	asciiTrans = true;
//			    		    }
//			    		    else if ( this.transTyper != null )
//			    		    {
//			    		    	if ( this.transTyper.isAsciiFile( eFile ) )
//			    		    	{
//			    		    		asciiTrans = true;
//			    		    	}
//			    		    }
//			    	} catch ( MimeTypeParseException ex )
//			    	{
//	//		    		 IGNORE THIS ERROR...
//			    	}
//		    	
//		    	if (this.debug) {
//		    		Console.Error.WriteLine("CREATE TRANS? '" + asciiTrans + "'  ContentType='" + contentType + "'  PrimaryType='" + mime.getPrimaryType()+ "'" );
//		    	}
		    	
		    	if (asciiTrans) {
		    		tempFileName = Path.GetTempFileName();
		    		
		    		StreamReader inStream  = File.OpenText(eFile);
		    		Stream       outStream = new BufferedStream(File.Create(tempFileName));
		    		
		    		while (true) {
		    			string line = inStream.ReadLine();
		    			if (line == null) {
		    				break;
		    			}
		    			byte[] data = Encoding.ASCII.GetBytes(line);
		    			outStream.Write(data, 0, data.Length);
		    			outStream.WriteByte((byte)'\n');
		    		}
		    		
		    		inStream.Close();

		    		outStream.Flush();
		    		outStream.Close();
		    		
		    		entry.Size = new FileInfo(tempFileName).Length;
		    		
		    		eFile = tempFileName;
		    	}
			}
		    
		    string newName = null;
		
			if (this.rootPath != null) {
				if (entry.Name.StartsWith(this.rootPath)) {
					newName = entry.Name.Substring(this.rootPath.Length + 1 );
				}
			}
			
			if (this.pathPrefix != null) {
				newName = (newName == null) ? this.pathPrefix + "/" + entry.Name : this.pathPrefix + "/" + newName;
			}
			
			if (newName != null) {
				entry.Name = newName;
			}
			
			this.tarOut.PutNextEntry(entry);
			
			if (entry.IsDirectory) {
				if (recurse) {
					TarEntry[] list = entry.GetDirectoryEntries();
					for (int i = 0; i < list.Length; ++i) {
						this.WriteEntry(list[i], recurse);
					}
				}
			}
         else {
				Stream inputStream = File.OpenRead(eFile);
				int numWritten = 0;
				byte[] eBuf = new byte[32 * 1024];
				while (true) {
					int numRead = inputStream.Read(eBuf, 0, eBuf.Length);
					
					if (numRead <=0) {
						break;
					}
					
					this.tarOut.Write(eBuf, 0, numRead);
					numWritten +=  numRead;
				}

//				Console.WriteLine("written " + numWritten + " bytes");
				
				inputStream.Close();
				
				if (tempFileName != null && tempFileName.Length > 0) {
					File.Delete(tempFileName);
				}
				
				this.tarOut.CloseEntry();
			}
		}
	 public void Position ()
	 {
		mem = new MemoryStream ();
		BufferedStream stream = new BufferedStream (mem,5);
		stream.Write (new byte [] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, 0, 16);
	 	
		stream.Position = 0;
		Assert.AreEqual (0, stream.Position, "test#01");		
		Assert.AreEqual (0, stream.ReadByte (), "test#02");		
		
		stream.Position = 5;
		Assert.AreEqual (5, stream.Position, "test#01");		
		Assert.AreEqual (5, stream.ReadByte (), "test#02");		
		
		// Should not need to read from the underlying stream:
		stream.Position = 7;
		Assert.AreEqual (7, stream.Position, "test#01");		
		Assert.AreEqual (7, stream.ReadByte (), "test#02");		
		
		// Should not need to read from the underlying stream:
		stream.Position = 5;
		Assert.AreEqual (5, stream.Position, "test#01");		
		Assert.AreEqual (5, stream.ReadByte (), "test#02");		
				
		// Should not need to read from the underlying stream:
		stream.Position = 9;
		Assert.AreEqual (9, stream.Position, "test#01");
		Assert.AreEqual (9, stream.ReadByte (), "test#02");
		
		stream.Position = 10;
		Assert.AreEqual (10, stream.Position, "test#01");		
		Assert.AreEqual (10, stream.ReadByte (), "test#02");		
		
		stream.Position = 9;
		Assert.AreEqual (9, stream.Position, "test#01");		
		Assert.AreEqual (9, stream.ReadByte (), "test#02");		
	 }
        public void With_WebSocket_FailsWithDoubleMessageAwait()
        {
            var handshake = GenerateSimpleHandshake();
            using (var ms = new BufferedStream(new MemoryStream()))
            using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions))
            {
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                ws.ReadMessage();
                ws.ReadMessage();
            }
        }
	public void Seek ()
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Write (new byte [] {0, 1, 2, 3, 4, 5}, 0, 6);
		
		Assert.AreEqual (6, stream.Position, "test#01");
		
		stream.Seek (-5, SeekOrigin.End);		
		Assert.AreEqual (1, stream.Position, "test#02");
		
		stream.Seek (3, SeekOrigin.Current);
		Assert.AreEqual (4, stream.Position, "test#03");
		
		stream.Seek (300, SeekOrigin.Current);		
		Assert.AreEqual (304, stream.Position, "test#04");		
	}
	public void SetLength ()
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Write (new byte [] {0,1,2,3,4,5}, 0, 6);
		
		Assert.AreEqual (6, stream.Length, "test#01");
		stream.SetLength (60);
		Assert.AreEqual (60, stream.Length, "test#02");
		
		stream.SetLength (2);
		Assert.AreEqual (2, stream.Length, "test#03");	
	}
	public void Flush ()
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.WriteByte (1);
		stream.WriteByte (2);
		
		byte [] bytes = mem.GetBuffer ();
		Assert.AreEqual (0, bytes.Length, "test#01");
		stream.Flush ();
		
		bytes = mem.GetBuffer ();
		Assert.AreEqual (256, bytes.Length, "test#02");
		Assert.AreEqual (1, bytes [0], "test#03");
		Assert.AreEqual (2, bytes [1], "test#04");
		mem.Close ();
		mem = new MemoryStream ();
		bytes = new byte [] {0, 1, 2, 3, 4, 5};
		stream = new BufferedStream (mem);
		stream.Write (bytes, 0, 2);
		Assert.AreEqual (2, stream.Length, "test#05");
		bytes = mem.GetBuffer ();
		Assert.AreEqual (256, bytes.Length, "test#06");

		Assert.AreEqual (0, bytes [0], "test#07");
		Assert.AreEqual (1, bytes [1], "test#08");
		
		stream.Write (bytes, 0, 2);
		
		bytes = mem.GetBuffer ();
		Assert.AreEqual (0, bytes [0], "test#09");
		Assert.AreEqual (1, bytes [1], "test#10");
		Assert.AreEqual (0, bytes [2], "test#11");
		Assert.AreEqual (0, bytes [3], "test#12");
		stream.Flush ();
		bytes = mem.GetBuffer ();
		Assert.AreEqual (0, bytes [2], "test#13");
		Assert.AreEqual (1, bytes [3], "test#14");
	}
	public void Write_CountOverflow () 
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Write (new byte [1], 1, Int32.MaxValue); 
	}
	public void Write_CountNegative () 
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Write (new byte [1], 1, -1); 
	}
	public void Write_OffsetOverflow () 
	{
		BufferedStream stream = new BufferedStream (mem);
		stream.Write (new byte [1], Int32.MaxValue, 1); 
	}
        /// <summary>
        /// Reads header from source stream and stores to the specified stream. Reads header data while 
        /// gets blank line, what is header terminator. For example this method can be used for reading 
        /// mail,http,sip, ... headers.
        /// </summary>
        /// <param name="storeStream">Stream where to store readed data.</param>
        /// <param name="maxSize">Maximum number of bytes to read.</param>
        /// <param name="exceededAction">Specifies how this method behaves when maximum line or data size exceeded.</param>
        /// <returns>Returns number of bytes written to <b>storeStream</b>.</returns>
        /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception>
        /// <exception cref="ArgumentException">Raised when <b>maxSize</b> less than 1.</exception>
        /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception>
        /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception>
        /// <exception cref="DataSizeExceededException">Raised when maximum allowed data size has exceeded.</exception>
        public int ReadHeader(Stream storeStream,int maxSize,SizeExceededAction exceededAction)
        {
            if(storeStream == null){
                throw new ArgumentNullException("storeStream");
            }
            lock(this){
                if(m_IsReadActive){
                    throw new InvalidOperationException("There is pending read operation, multiple read operations not allowed !");
                }
                else{
                    m_IsReadActive = true;
                }
            }

            try{
                BufferedStream bufferedStoreStream = new BufferedStream(storeStream,32000);
                bool lineSizeExceeded = false;
                int  totalReadedCount = 0;
                int  readedCount      = 0;
                int  rawReadedCount   = 0;
                while(true){
                    // Read line.
                    readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.ThrowException,out rawReadedCount,false);

                    // We have reached end of stream, no more data.
                    if(rawReadedCount == 0){
                        break;
                    }
                    totalReadedCount += rawReadedCount;

                    // We got header terminator.
                    if(readedCount == 0){
                        break;
                    }
                    else{
                        // Maximum allowed data size exceeded.
                        if(totalReadedCount > maxSize){
                            if(exceededAction == SizeExceededAction.ThrowException){
                                throw new DataSizeExceededException();
                            }
                        }
                        // Write readed bytes to store stream.
                        else{
                            bufferedStoreStream.Write(m_pLineBuffer,0,readedCount);
                            bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length);
                        }
                    }
                }
                bufferedStoreStream.Flush();

                // Maximum allowed line size exceeded, some data is junked.
                if(lineSizeExceeded){
                    throw new LineSizeExceededException();
                }
                // Maximum allowed data size exceeded, some data is junked.
                if(totalReadedCount > maxSize){
                    throw new DataSizeExceededException();
                }

                // Log
                if(this.Logger != null){
                    this.Logger.AddRead(totalReadedCount,null);
                }

                return totalReadedCount;
            }
            finally{
                m_IsReadActive = false;
            }
        }
        /// <summary>
        /// Reads period terminated data from source stream. Reads data while gets single period on line,
        /// what is data terminator.
        /// </summary>
        /// <param name="storeStream">Stream where to store readed data.</param>
        /// <param name="maxSize">Maximum number of bytes to read.</param>
        /// <param name="exceededAction">Specifies how this method behaves when maximum size exceeded.</param>
        /// <returns>Returns number of bytes written to <b>storeStream</b>.</returns>
        /// <exception cref="ArgumentNullException">Raised when <b>storeStream</b> is null.</exception>
        /// <exception cref="ArgumentException">Raised when <b>maxSize</b> less than 1.</exception>
        /// <exception cref="InvalidOperationException">Raised when there already is pending read operation.</exception>
        /// <exception cref="LineSizeExceededException">Raised when maximum allowed line size has exceeded.</exception>
        /// <exception cref="DataSizeExceededException">Raised when maximum allowed data size has exceeded.</exception>
        /// <exception cref="IncompleteDataException">Raised when source stream was reached end of stream and data is not period terminated.</exception>
        public int ReadPeriodTerminated(Stream storeStream,int maxSize,SizeExceededAction exceededAction)
        {
            if(storeStream == null){
                throw new ArgumentNullException("storeStream");
            }
            lock(this){
                if(m_IsReadActive){
                    throw new InvalidOperationException("There is pending read operation, multiple read operations not allowed !");
                }
                else{
                    m_IsReadActive = true;
                }
            }

            try{
                BufferedStream bufferedStoreStream = new BufferedStream(storeStream,32000);
                bool lineSizeExceeded   = false;
                bool isPeriodTerminated = false;
                int  totalReadedCount   = 0;
                int  readedCount        = 0;
                int  rawReadedCount     = 0;

                // Just break reading at once if maximum allowed line or data size exceeded.
                if(exceededAction == SizeExceededAction.ThrowException){
                    try{
                        // Read first line.
                        readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.JunkAndThrowException,out rawReadedCount,false);
                    }
                    catch(LineSizeExceededException x){
                        string dummy = x.Message;
                        lineSizeExceeded = true;
                    }
                    while(rawReadedCount != 0){
                        totalReadedCount += rawReadedCount;

                        // We have data terminator "<CRLF>.<CRLF>".
                        if(readedCount == 1 && m_pLineBuffer[0] == '.'){
                            isPeriodTerminated = true;
                            break;
                        }
                        // If line starts with period(.), first period is removed.
                        else if(m_pLineBuffer[0] == '.'){
                            // Maximum allowed line or data size exceeded.
                            if(lineSizeExceeded || totalReadedCount > maxSize){
                                // Junk data
                            }
                            // Write readed line to store stream.
                            else{
                                bufferedStoreStream.Write(m_pLineBuffer,1,readedCount - 1);
                                bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length);
                            }
                        }
                        // Normal line.
                        else{
                            // Maximum allowed line or data size exceeded.
                            if(lineSizeExceeded || totalReadedCount > maxSize){
                                // Junk data
                            }
                            // Write readed line to store stream.
                            else{
                                bufferedStoreStream.Write(m_pLineBuffer,0,readedCount);
                                bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length);
                            }
                        }

                        try{
                            // Read next line.
                            readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.JunkAndThrowException,out rawReadedCount,false);
                        }
                        catch(LineSizeExceededException x){
                            string dummy = x.Message;
                            lineSizeExceeded = true;
                        }
                    }
                }
                // Read and junk all data if maximum allowed line or data size exceeded.
                else{
                    // Read first line.
                    readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.JunkAndThrowException,out rawReadedCount,false);
                    while(rawReadedCount != 0){
                        totalReadedCount += rawReadedCount;

                        // We have data terminator "<CRLF>.<CRLF>".
                        if(readedCount == 1 && m_pLineBuffer[0] == '.'){
                            isPeriodTerminated = true;
                            break;
                        }
                        // If line starts with period(.), first period is removed.
                        else if(m_pLineBuffer[0] == '.'){
                            // Maximum allowed size exceeded.
                            if(totalReadedCount > maxSize){
                                throw new DataSizeExceededException();
                            }

                            // Write readed line to store stream.
                            bufferedStoreStream.Write(m_pLineBuffer,1,readedCount - 1);
                            bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length);
                        }
                        // Normal line.
                        else{
                            // Maximum allowed size exceeded.
                            if(totalReadedCount > maxSize){
                                throw new DataSizeExceededException();
                            }

                            // Write readed line to store stream.
                            bufferedStoreStream.Write(m_pLineBuffer,0,readedCount);
                            bufferedStoreStream.Write(m_LineBreak,0,m_LineBreak.Length);
                        }

                        // Read next line.
                        readedCount = this.ReadLineInternal(m_pLineBuffer,SizeExceededAction.JunkAndThrowException,out rawReadedCount,false);
                    }
                }
                bufferedStoreStream.Flush();

                // Log
                if(this.Logger != null){
                    this.Logger.AddRead(totalReadedCount,null);
                }

                if(lineSizeExceeded){
                    throw new LineSizeExceededException();
                }
                if(!isPeriodTerminated){
                    throw new IncompleteDataException("Source stream was reached end of stream and data is not period terminated !");
                }
                if(totalReadedCount > maxSize){
                    throw new DataSizeExceededException();
                }

                return totalReadedCount;
            }
            finally{
                m_IsReadActive = false;
            }
        }
Exemple #36
0
    /* add a jpeg frame to an AVI file */
    public void avi_add(u8[] buf, uint size)
    {
        lock (locker)
        {
            uint osize = size;
            Console.WriteLine(DateTime.Now.Millisecond + " avi frame");
            db_head db = new db_head {
                db = "00dc".ToCharArray(), size = size
            };
            fd.Write(StructureToByteArray(db), 0, Marshal.SizeOf(db));
            uint offset = (uint)fd.Position;
            fd.Write(buf, 0, (int)size);

            indexs.Add(new AVIINDEXENTRY()
            {
                ckid = "00dc".ToCharArray(), dwChunkLength = size, dwChunkOffset = (offset - 8212 + 4), dwFlags = 0x10
            });

            while (fd.Position % 2 != 0)
            {
                size++;
                fd.WriteByte(0);
                //fd.Seek(1, SeekOrigin.Current);
            }
            nframes++;
            totalsize += size;

            if (((DateTime.Now - start).TotalSeconds * targetfps) > nframes)
            {
                avi_add(buf, osize);
                Console.WriteLine("Extra frame");
            }
        }
    }