System.IO.Stream.Write(byte[], int, int)

Here are the examples of the csharp api System.IO.Stream.Write(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4203 Examples 7

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool ReplyIndex(HttpListenerContext ctx, string statusMessage)
        {
            string content = cachedIndexHtml.Replace("%%STATUS_MESSAGE%%", statusMessage);

            byte[] data = Encoding.ASCII.GetBytes(content);

            try
            {
                ctx.Response.ContentLength64 = data.Length;
                ctx.Response.StatusCode = 200;

                ctx.Response.ContentEncoding = Encoding.ASCII;
                ctx.Response.ContentType = "text/html";
                ctx.Response.OutputStream.Write(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                data = null;
                return false;
            }

            data = null;
            return true;
        }

19 View Source File : CelesteNetClientRC.cs
License : MIT License
Project Creator : 0x0ade

public static void Write(HttpListenerContext c, string str) {
            byte[] buf = CelesteNetUtils.UTF8NoBOM.GetBytes(str);
            c.Response.ContentLength64 = buf.Length;
            c.Response.OutputStream.Write(buf, 0, buf.Length);
        }

19 View Source File : DisposeActionStream.cs
License : MIT License
Project Creator : 0x0ade

public override void Write(byte[] buffer, int offset, int count) => Inner.Write(buffer, offset, count);

19 View Source File : PositionAwareStream.cs
License : MIT License
Project Creator : 0x0ade

public override void Write(byte[] buffer, int offset, int count) {
            Inner.Write(buffer, offset, count);
            _Position += count;
        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 View Source File : HeifStreamWriter.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054

protected override void WriteCore(IntPtr data, long count)
        {
            long offset = 0;
            long remaining = count;

            while (remaining > 0)
            {
                int copySize = (int)Math.Min(MaxWriteBufferSize, remaining);

                Marshal.Copy(new IntPtr(data.ToInt64() + offset), this.streamBuffer, 0, copySize);

                this.stream.Write(this.streamBuffer, 0, copySize);

                offset += copySize;
                remaining -= copySize;
            }
        }

19 View Source File : StreamIOCallbacks.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe int Write(IntPtr buffer, uint count, uint* bytesWritten)
        {
            if (bytesWritten != null)
            {
                *bytesWritten = 0;
            }

            if (count == 0)
            {
                return HResult.S_OK;
            }

            try
            {
                long offset = 0;
                long remaining = count;

                do
                {
                    int copySize = (int)Math.Min(MaxBufferSize, remaining);

                    Marshal.Copy(new IntPtr(buffer.ToInt64() + offset), this.streamBuffer, 0, copySize);

                    this.stream.Write(this.streamBuffer, 0, copySize);

                    offset += copySize;
                    remaining -= copySize;

                } while (remaining > 0);

                if (bytesWritten != null)
                {
                    *bytesWritten = count;
                }

                return HResult.S_OK;
            }
            catch (Exception ex)
            {
                this.CallbackExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                return ex.HResult;
            }
        }

19 View Source File : BigEndianBinaryWriter.cs
License : MIT License
Project Creator : 0xC0000054

public void Write(ushort value)
        {
            VerifyNotDisposed();

            this.buffer[0] = (byte)((value >> 8) & 0xff);
            this.buffer[1] = (byte)(value & 0xff);

            this.stream.Write(this.buffer, 0, 2);
        }

19 View Source File : BigEndianBinaryWriter.cs
License : MIT License
Project Creator : 0xC0000054

public void Write(uint value)
        {
            VerifyNotDisposed();

            this.buffer[0] = (byte)((value >> 24) & 0xff);
            this.buffer[1] = (byte)((value >> 16) & 0xff);
            this.buffer[2] = (byte)((value >> 8) & 0xff);
            this.buffer[3] = (byte)(value & 0xff);

            this.stream.Write(this.buffer, 0, 4);
        }

19 View Source File : BigEndianBinaryWriter.cs
License : MIT License
Project Creator : 0xC0000054

public void Write(ulong value)
        {
            VerifyNotDisposed();

            this.buffer[0] = (byte)((value >> 56) & 0xff);
            this.buffer[1] = (byte)((value >> 48) & 0xff);
            this.buffer[2] = (byte)((value >> 40) & 0xff);
            this.buffer[3] = (byte)((value >> 32) & 0xff);
            this.buffer[4] = (byte)((value >> 24) & 0xff);
            this.buffer[5] = (byte)((value >> 16) & 0xff);
            this.buffer[6] = (byte)((value >> 8) & 0xff);
            this.buffer[7] = (byte)(value & 0xff);

            this.stream.Write(this.buffer, 0, 8);
        }

19 View Source File : BigEndianBinaryWriter.cs
License : MIT License
Project Creator : 0xC0000054

public void Write(byte[] bytes, int offset, int count)
        {
            VerifyNotDisposed();

            this.stream.Write(bytes, offset, count);
        }

19 View Source File : BigEndianBinaryWriter.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe void Write(SafeBuffer buffer)
        {
            if (buffer is null)
            {
                ExceptionUtil.ThrowArgumentNullException(nameof(buffer));
            }

            VerifyNotDisposed();

            ulong length = buffer.ByteLength;

            if (length == 0)
            {
                return;
            }

            // The largest multiple of 4096 that is under the large object heap limit.
            const int MaxBufferSize = 81920;

            int bufferSize = (int)Math.Min(length, MaxBufferSize);

            using (IArrayPoolBuffer<byte> poolBuffer = this.arrayPool.Rent<byte>(bufferSize))
            {
                byte[] writeBuffer = poolBuffer.Array;

                byte* readPtr = null;
                try
                {
                    buffer.AcquirePointer(ref readPtr);

                    fixed (byte* writePtr = writeBuffer)
                    {
                        ulong totalBytesRead = 0;

                        while (totalBytesRead < length)
                        {
                            ulong bytesRead = Math.Min(length - totalBytesRead, MaxBufferSize);

                            Buffer.MemoryCopy(readPtr + totalBytesRead, writePtr, bytesRead, bytesRead);

                            this.stream.Write(writeBuffer, 0, (int)bytesRead);

                            totalBytesRead += bytesRead;
                        }
                    }
                }
                finally
                {
                    if (readPtr != null)
                    {
                        buffer.ReleasePointer();
                    }
                }
            }
        }

19 View Source File : DX9DdsWriter.cs
License : MIT License
Project Creator : 0xC0000054

private unsafe void WritePixelData(Surface surface, Stream output)
        {
            for (int y = 0; y < surface.Height; ++y)
            {
                ColorBgra* ptr = surface.GetRowPointerUnchecked(y);
                ColorBgra* ptrEnd = ptr + surface.Width;

                while (ptr < ptrEnd)
                {
                    switch (this.format)
                    {
                        case DdsFileFormat.R8G8B8X8:
                            this.pixelBuffer[0] = ptr->R;
                            this.pixelBuffer[1] = ptr->G;
                            this.pixelBuffer[2] = ptr->B;
                            break;
                        case DdsFileFormat.B8G8R8:
                            this.pixelBuffer[0] = ptr->B;
                            this.pixelBuffer[1] = ptr->G;
                            this.pixelBuffer[2] = ptr->R;
                            break;
                        default:
                            throw new InvalidOperationException(GetUnsupportedFormatMessage(this.format));
                    }

                    output.Write(this.pixelBuffer, 0, this.pixelBuffer.Length);

                    ptr++;
                }
            }
        }

19 View Source File : WebPNative.cs
License : MIT License
Project Creator : 0xC0000054

[System.Diagnostics.Codereplacedysis.SuppressMessage(
                "Microsoft.Design",
                "CA1031:DoNotCatchGeneralExceptionTypes",
                Justification = "The exception will be re-thrown after WebPSave returns the error code.")]
            public WebPEncodingError WriteImageCallback(IntPtr image, UIntPtr imageSize)
            {
                if (image == IntPtr.Zero)
                {
                    return WebPEncodingError.NullParameter;
                }

                if (imageSize == UIntPtr.Zero)
                {
                    // Ignore zero-length images.
                    return WebPEncodingError.Ok;
                }

                // 81920 is the largest multiple of 4096 that is below the large object heap threshold.
                const int MaxBufferSize = 81920;

                try
                {
                    long size = checked((long)imageSize.ToUInt64());

                    int bufferSize = (int)Math.Min(size, MaxBufferSize);

                    byte[] streamBuffer = new byte[bufferSize];

                    output.SetLength(size);

                    long offset = 0;
                    long remaining = size;

                    while (remaining > 0)
                    {
                        int copySize = (int)Math.Min(MaxBufferSize, remaining);

                        Marshal.Copy(new IntPtr(image.ToInt64() + offset), streamBuffer, 0, copySize);

                        output.Write(streamBuffer, 0, copySize);

                        offset += copySize;
                        remaining -= copySize;
                    }
                }
                catch (OperationCanceledException)
                {
                    return WebPEncodingError.UserAbort;
                }
                catch (Exception ex)
                {
                    WriteException = ex;
                    return WebPEncodingError.BadWrite;
                }

                return WebPEncodingError.Ok;
            }

19 View Source File : BufferSpan.cs
License : MIT License
Project Creator : 1996v

internal void WriteTo(Stream stream, int count)
        {
            stream.Write(Buffer, Start, count);
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

void EndRequest(IAsyncResult ar)
        {
            StateObject state = ar.AsyncState as StateObject;
            try
            {
                HttpWebRequest webRequest = state.HttpWebRequest as HttpWebRequest;
                webRequest.Timeout = 20 * 1000;
                using (Stream stream = webRequest.EndGetRequestStream(ar))
                {
                    byte[] data = state.ResponseInfo.RequestInfo.PostData;
                    stream.Write(data, 0, data.Length);
                }
                webRequest.BeginGetResponse(EndResponse, state);

            }
            catch (Exception ex)
            {
                HandException(ex, state);
            }
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

void ReadCallBack(IAsyncResult ar)
        {
            StateObject state = ar.AsyncState as StateObject;
            try
            {
                int read = state.ReadStream.EndRead(ar);
                if (read > 0)
                {
                    state.ResponseInfo.ResponseContent.Write(state.Buffer, 0, read);
                    state.ReadStream.BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallBack, state);
                }
                else
                {
                    state.ReadStream.Close();
                    state.HttpWebRequest.Abort();
                    if (state.Action != null)
                    {
                        state.Action(state.ResponseInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                HandException(ex, state);
            }
        }

19 View Source File : RedisReader.cs
License : MIT License
Project Creator : 2881099

public void ReadBulkBytes(Stream destination, int bufferSize, bool checkType = true)
        {
            if (checkType)
                ExpectType(RedisMessage.Bulk);
            int size = (int)ReadInt(false);
            if (size == -1)
                return;

            byte[] buffer = new byte[bufferSize];
            int position = 0;
            while (position < size)
            {
                int bytes_to_buffer = Math.Min(buffer.Length, size - position);
                int bytes_read = 0;
                while (bytes_read < bytes_to_buffer)
                {
                    int bytes_to_read = Math.Min(bytes_to_buffer - bytes_read, size - position);
                    bytes_read += _io.Read(buffer, bytes_read, bytes_to_read);
                }
                position += bytes_read;
                destination.Write(buffer, 0, bytes_read);
            }
            //Console.WriteLine($"ReadBulkBytes2: {Encoding.UTF8.GetString(buffer)}");
            ExpectBytesRead(size, position);
            ReadCRLF();
        }

19 View Source File : RedisIO.cs
License : MIT License
Project Creator : 2881099

public void Write(byte[] data)
        {
            lock (_streamLock)
            {
                Stream.Write(data, 0, data.Length);
                Stream.Flush();
            }
        }

19 View Source File : Compression.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static void CopyTo(Stream src, Stream dest)
        {
            byte[] bytes = new byte[4096];

            int cnt;

            while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
            {
                dest.Write(bytes, 0, cnt);
            }
        }

19 View Source File : HttpClient.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo

protected T_out HttpPostJson<T_in, T_out>(string uri, T_in data)
        {
            AppendApiKey(ref uri);

            // put together the json object with the login form data
            string parameters = JsonMapper.ToJson(data);
            byte[] postDataBuffer = Encoding.UTF8.GetBytes(parameters);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.ContentLength = postDataBuffer.Length;
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("POST " + uri + " data: " + parameters);

            Stream postDataStream = request.GetRequestStream();

            postDataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
            postDataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            StreamReader responseReader = new StreamReader(responseStream);
            string responseData = responseReader.ReadToEnd();

            Cookie responseCookie = response.Cookies[0];
            string responseDomain = responseCookie.Domain;

            // Only replacedume one cookie per domain
            if (!cookieDict.ContainsKey(responseDomain))
            {
                cookieDict.Add(responseCookie.Domain, responseCookie);
                responseCookie.Domain = "." + responseCookie.Domain;
            }

            Uri myUri = new Uri(uri);

            foreach (KeyValuePair<string, Cookie> entry in cookieDict)
            {
                int uriHostLength = myUri.Host.Length;

                if (myUri.Host.Substring(uriHostLength - responseDomain.Length, responseDomain.Length) == entry.Key)
                {
                    cookies.Add(myUri, entry.Value);
                }
            }

            return JsonMapper.ToObject<T_out>(responseData);
        }

19 View Source File : MP3FileWriter.cs
License : MIT License
Project Creator : 3wz

public override void Flush()
        {
            // write remaining data
            if (inPosition > 0)
                Encode();

            // finalize compression
            int rc = _lame.Flush(outBuffer, outBuffer.Length);
            if (rc > 0)
                outStream.Write(outBuffer, 0, rc);

            // Cannot continue after flush, so clear output stream
            if (disposeOutput)
                outStream.Dispose();
            outStream = null;
        }

19 View Source File : ExtendUtility.cs
License : MIT License
Project Creator : 3wz

public static void CopyTo(this Stream input, Stream output)
    {
        byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
        int bytesRead;

        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
    }

19 View Source File : MP3FileWriter.cs
License : MIT License
Project Creator : 3wz

private void Encode()
        {
            // check if encoder closed
            if (outStream == null || _lame == null)
                throw new InvalidOperationException("Output Stream closed.");

            // If no data to encode, do nothing
            if (inPosition < inputFormat.Channels * 2)
                return;

            // send to encoder
            int rc = _encode();

            if (rc > 0)
            {
                outStream.Write(outBuffer, 0, rc);
                OutputByteCount += rc;
            }

            InputByteCount += inPosition;
            inPosition = 0;
        }

19 View Source File : ProtoWriter.cs
License : MIT License
Project Creator : 404Lcc

private static void CopyRawFromStream(Stream source, ProtoWriter writer)
        {
            byte[] buffer = writer.ioBuffer;
            int space = buffer.Length - writer.ioIndex, bytesRead = 1; // 1 here to spoof case where already full
            
            // try filling the buffer first   
            while (space > 0 && (bytesRead = source.Read(buffer, writer.ioIndex, space)) > 0)
            {
                writer.ioIndex += bytesRead;
                writer.position64 += bytesRead;
                space -= bytesRead;                
            }
            if (bytesRead <= 0) return; // all done using just the buffer; stream exhausted

            // at this point the stream still has data, but buffer is full; 
            if (writer.flushLock == 0)
            {
                // flush the buffer and write to the underlying stream instead
                Flush(writer);
                while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    writer.dest.Write(buffer, 0, bytesRead);
                    writer.position64 += bytesRead;
                }
            }
            else
            {
                do
                {
                    // need more space; resize (double) as necessary,
                    // requesting a reasonable minimum chunk each time
                    // (128 is the minimum; there may actually be much
                    // more space than this in the buffer)
                    DemandSpace(128, writer);
                    if((bytesRead = source.Read(writer.ioBuffer, writer.ioIndex,
                        writer.ioBuffer.Length - writer.ioIndex)) <= 0) break;
                    writer.position64 += bytesRead;
                    writer.ioIndex += bytesRead;
                } while (true);
            }

        }

19 View Source File : ProtoWriter.cs
License : MIT License
Project Creator : 404Lcc

internal static void Flush(ProtoWriter writer)
        {
            if (writer.flushLock == 0 && writer.ioIndex != 0)
            {
                writer.dest.Write(writer.ioBuffer, 0, writer.ioIndex);
                writer.ioIndex = 0;                
            }
        }

19 View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344

public void Add(DateTime datetime)
        {
            var value = (uint) (datetime - DateTime.Parse("1970-1-1").ToLocalTime()).TotalSeconds;
            var bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            _stream.Write(bytes, 0, bytes.Length);
        }

19 View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344

public void Add(string hilString)
        {
            var array = Util.HexStringToByteArray(hilString);
            _stream.Write(array, 0, array.Length);
        }

19 View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344

public void Add(uint item)
        {
            var bytes = BitConverter.GetBytes(item);
            _stream.Write(bytes, 0, bytes.Length);
        }

19 View Source File : CodedOutputStream.cs
License : MIT License
Project Creator : 404Lcc

internal void WriteRawBytes(byte[] value, int offset, int length)
        {
            if (limit - position >= length)
            {
                ByteArray.Copy(value, offset, buffer, position, length);
                // We have room in the current buffer.
                position += length;
            }
            else
            {
                // Write extends past current buffer.  Fill the rest of this buffer and
                // flush.
                int bytesWritten = limit - position;
                ByteArray.Copy(value, offset, buffer, position, bytesWritten);
                offset += bytesWritten;
                length -= bytesWritten;
                position = limit;
                RefreshBuffer();

                // Now deal with the rest.
                // Since we have an output stream, this is our buffer
                // and buffer offset == 0
                if (length <= limit)
                {
                    // Fits in new buffer.
                    ByteArray.Copy(value, offset, buffer, 0, length);
                    position = length;
                }
                else
                {
                    // Write is very big.  Let's do it all at once.
                    output.Write(value, offset, length);
                }
            }
        }

19 View Source File : CodedOutputStream.cs
License : MIT License
Project Creator : 404Lcc

private void RefreshBuffer()
        {
            if (output == null)
            {
                // We're writing to a single buffer.
                throw new OutOfSpaceException();
            }

            // Since we have an output stream, this is our buffer
            // and buffer offset == 0
            output.Write(buffer, 0, position);
            position = 0;
        }

19 View Source File : ProtoWriter.cs
License : MIT License
Project Creator : 404Lcc

public static void WriteBytes(byte[] data, int offset, int length, ProtoWriter writer)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (writer == null) throw new ArgumentNullException("writer");
            switch (writer.wireType)
            {
                case WireType.Fixed32:
                    if (length != 4) throw new ArgumentException("length");
                    goto CopyFixedLength;  // ugly but effective
                case WireType.Fixed64:
                    if (length != 8) throw new ArgumentException("length");
                    goto CopyFixedLength;  // ugly but effective
                case WireType.String:
                    WriteUInt32Variant((uint)length, writer);
                    writer.wireType = WireType.None;
                    if (length == 0) return;
                    if (writer.flushLock != 0 || length <= writer.ioBuffer.Length) // write to the buffer
                    {
                        goto CopyFixedLength; // ugly but effective
                    }
                    // writing data that is bigger than the buffer (and the buffer
                    // isn't currently locked due to a sub-object needing the size backfilled)
                    Flush(writer); // commit any existing data from the buffer
                    // now just write directly to the underlying stream
                    writer.dest.Write(data, offset, length);
                    writer.position64 += length; // since we've flushed offset etc is 0, and remains
                                        // zero since we're writing directly to the stream
                    return;
            }
            throw CreateException(writer);
        CopyFixedLength: // no point duplicating this lots of times, and don't really want another stackframe
            DemandSpace(length, writer);
            Helpers.BlockCopy(data, offset, writer.ioBuffer, writer.ioIndex, length);
            IncrementedAndReset(length, writer);
        }

19 View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344

public void Add(byte[] item)
        {
            _stream.Write(item, 0, item.Length);
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : 5minlab

public static void WriteString(this HttpListenerResponse response, string input, string type = "text/plain") {
            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusDescription = "OK";

            if (!string.IsNullOrEmpty(input)) {
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(input);
                response.ContentLength64 = buffer.Length;
                response.ContentType = type;
                response.OutputStream.Write(buffer, 0, buffer.Length);
            }
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : 5minlab

public static void WriteBytes(this HttpListenerResponse response, byte[] bytes) {
            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusDescription = "OK";
            response.ContentLength64 = bytes.Length;
            response.OutputStream.Write(bytes, 0, bytes.Length);
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : 5minlab

public static void WriteFile(this HttpListenerResponse response, string path, string type = "application/octet-stream", bool download = false) {
            using (FileStream fs = File.OpenRead(path)) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.ContentLength64 = fs.Length;
                response.ContentType = type;
                if (download)
                    response.AddHeader("Content-disposition", string.Format("attachment; filename={0}", Path.GetFileName(path)));

                byte[] buffer = new byte[64 * 1024];
                int read;
                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) {
                    // FIXME required?
                    System.Threading.Thread.Sleep(0);
                    response.OutputStream.Write(buffer, 0, read);
                }
            }
        }

19 View Source File : Utility.Http.cs
License : MIT License
Project Creator : 7Bytes-Studio

public void Start()
                {
                    if (IsWorking) return;

                    try
                    {
                        m_HttpListener = new HttpListener();
                        //监听的路径
                        m_HttpListener.Prefixes.Add(Address + "/");
                        for (int i = 0; i < Prefixes.Length; i++)
                        {
                            m_HttpListener.Prefixes.Add(Prefixes[i]);
                        }
                        //设置匿名访问
                        m_HttpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                        m_HttpListener.Start();

                        if (null != m_HttpServerInfo.OnStartSucceed)
                        {
                            m_HttpServerInfo.OnStartSucceed.Invoke(this, EventArgs.Empty);
                        }

                        IsWorking = true;



                        while (IsWorking)
                        {
                            var context = m_HttpListener.GetContext();
                            HttpListenerRequest request = context.Request;
                            HttpListenerResponse response = context.Response;
                            response.ContentEncoding = Encoding.UTF8;
                            response.AddHeader("Access-Control-Allow-Origin", "*"); //允许跨域请求。

                            byte[] handleContent = null;
                            if (request.HttpMethod == "GET")
                            {
                                if (null != m_HttpServerInfo.GetHandler)
                                {
                                    handleContent = m_HttpServerInfo.GetHandler.Invoke(request);
                                }

                            }
                            else if (request.HttpMethod == "POST")
                            {
                                if (null != m_HttpServerInfo.PostHandler)
                                {
                                    handleContent = m_HttpServerInfo.PostHandler.Invoke(request);
                                }
                            }
                            else
                            {
                                if (null != m_HttpServerInfo.DefaultHandler)
                                {
                                    handleContent = m_HttpServerInfo.DefaultHandler.Invoke(request);
                                }
                            }

                            if (null!= m_HttpServerInfo.OnBeforeResponse)
                            {
                                m_HttpServerInfo.OnBeforeResponse.Invoke(response);
                            }

                            response.ContentLength64 = handleContent.Length;
                            Stream output = response.OutputStream;
                            output.Write(handleContent, 0, handleContent.Length);
                            output.Close();
                        }

                        m_HttpListener.Close();
                        m_HttpListener.Abort();
                    }
                    catch (Exception ex)
                    {
                        IsWorking = false;
                        if (null != m_HttpServerInfo.OnStartFailure)
                        {
                            m_HttpServerInfo.OnStartFailure.Invoke(this,new StartFailureEventArgs(ex));
                        }
                    }








                }

19 View Source File : OutBuffer.cs
License : MIT License
Project Creator : 91Act

public void FlushData()
		{
			if (m_Pos == 0)
				return;
			m_Stream.Write(m_Buffer, 0, (int)m_Pos);
			m_Pos = 0;
		}

19 View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635

private void SetPostData(HttpItem item)
        {
            //验证在得到结果时是否有传入数据
            if (!request.Method.Trim().ToLower().Contains("get"))
            {
                if (item.PostEncoding != null)
                {
                    postencoding = item.PostEncoding;
                }
                byte[] buffer = null;
                //写入Byte类型
                if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
                {
                    //验证在得到结果时是否有传入数据
                    buffer = item.PostdataByte;
                }//写入文件
                else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata))
                {
                    StreamReader r = new StreamReader(item.Postdata, postencoding);
                    buffer = postencoding.GetBytes(r.ReadToEnd());
                    r.Close();
                } //写入字符串
                else if (!string.IsNullOrWhiteSpace(item.Postdata))
                {
                    buffer = postencoding.GetBytes(item.Postdata);
                }
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
                else
                {
                    request.ContentLength = 0;
                }
            }
        }

19 View Source File : LzmaEncoder.cs
License : MIT License
Project Creator : 91Act

public void WriteCoderProperties(System.IO.Stream outStream)
		{
			properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
			for (int i = 0; i < 4; i++)
				properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF);
			outStream.Write(properties, 0, kPropSize);
		}

19 View Source File : LzOutWindow.cs
License : MIT License
Project Creator : 91Act

public void Flush()
		{
			uint size = _pos - _streamPos;
			if (size == 0)
				return;
			_stream.Write(_buffer, (int)_streamPos, (int)size);
			if (_pos >= _windowSize)
				_pos = 0;
			_streamPos = _pos;
		}

19 View Source File : WebServer.cs
License : Apache License 2.0
Project Creator : A7ocin

void OnGetContext(IAsyncResult async)
        {
            // start listening for the next request
            _listener.BeginGetContext(OnGetContext, null);
            var context = _listener.EndGetContext(async);
            try
            {
                if (context.Request.RawUrl == "/")
                {
                    Debug.Log("[WebServer] context.Request.RawUrl");
                    context.Response.StatusCode = 200;
                    var process = System.Diagnostics.Process.GetCurrentProcess();
                    string msg = string.Format(@"<html><body><h1>UMA Simple Web Server</h1><table>
						<tr><td>Host Application</td><td>{0} (Process Id: {1})</td></tr>
						<tr><td>Working Directory</td><td>{2}</td></tr>
						</table><br><br>{3}</body></html>", process.ProcessName, process.Id, System.IO.Directory.GetCurrentDirectory(), GetLog("<br>"));
                    var data = System.Text.Encoding.UTF8.GetBytes(msg);
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    context.Response.OutputStream.Close();
                    //Tried adding response close aswell like in Adamas original
                    context.Response.Close();
                }
                else
                {
                    var filePath = System.IO.Path.Combine(_hostedFolder, context.Request.RawUrl.Substring(1));
                    if (System.IO.File.Exists(filePath))
                    {
                        using (var file = System.IO.File.Open(filePath, System.IO.FileMode.Open))
                        {
                            var buffer = new byte[file.Length];
                            file.Read(buffer, 0, (int)file.Length);
                            context.Response.ContentLength64 = file.Length;
                            context.Response.StatusCode = 200;
                            context.Response.OutputStream.Write(buffer, 0, (int)file.Length);
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                        UnityEngine.Debug.LogErrorFormat("Url not served. Have you built your replacedet Bundles? Url not served from: {0} '{1}'", context.Request.RawUrl, filePath);
#if UNITY_EDITOR
                        replacedetBundleManager.SimulateOverride = true;
                        context.Response.OutputStream.Close();
                        //Tried adding response close aswell like in Adamas original
                        context.Response.Abort();
                        return;
#endif
                    }
                }
                lock (_requestLog)
                {
                    _requestLog.Add(string.Format("{0} {1}", context.Response.StatusCode, context.Request.Url));
                }
                context.Response.OutputStream.Close();
                context.Response.Close();
            }
            catch (HttpListenerException e)
            {
                if (e.ErrorCode == -2147467259)
                {
                    // shutdown, terminate silently
                    Debug.LogWarning("[Web Server] ErrorCode -2147467259: terminate silently");
                    context.Response.Abort();
                    return;
                }
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
                context.Response.Abort();
            }
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

private string DoMethod(NameValueCollection jParams)
	    {
		    const int RequestTimeoutMilliseconds = 2*1000; // 2 sec 

		    string tempResult = "";

		    try
		    {
			    lock (m_tonceLock)
			    {
				    //get tonce
				    TimeSpan timeSpan = DateTime.UtcNow - genesis;
				    long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
				    jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
				    //mock json request id
				    jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
				    //build http head
				    string paramsHash = GetHMACSHA1Hash(jParams);
				    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
				    string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
				                      jParams[pId] + "}";

				    //get webrequest,respawn new object per call for multiple connections
				    var webRequest = (HttpWebRequest) WebRequest.Create(url);
				    webRequest.Timeout = RequestTimeoutMilliseconds;

				    var bytes = Encoding.ASCII.GetBytes(postData);

				    webRequest.Method = jParams[pRequestMethod];
				    webRequest.ContentType = "application/json-rpc";
				    webRequest.ContentLength = bytes.Length;
				    webRequest.Headers["Authorization"] = "Basic " + base64String;
				    webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];

				    // Send the json authentication post request
				    using (var dataStream = webRequest.GetRequestStream())
				    {
					    dataStream.Write(bytes, 0, bytes.Length);
				    }

				    // Get authentication response
				    using (var response = webRequest.GetResponse())
				    {
					    using (var stream = response.GetResponseStream())
					    {
// ReSharper disable once replacedignNullToNotNullAttribute
						    using (var reader = new StreamReader(stream))
						    {
							    tempResult = reader.ReadToEnd();
						    }
					    }
				    }
			    }
		    }
		    catch (WebException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
		    }

		    //there are two kinds of API response, result or error.
		    if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
		    }

		    //compare response id with request id and remove it from result
		    try
		    {
			    int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
			    string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
			    if (idString != jParams[pId])
			    {
				    throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
			    }
			    else
			    {
				    //remove json request id from response json string
				    int fromComma = tempResult.LastIndexOf(',');
				    int toLastBrace = tempResult.Length - 1;
				    tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
			    }
		    }
		    catch (ArgumentOutOfRangeException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
		    }

		    return tempResult;
	    }

19 View Source File : AppenderBase.cs
License : MIT License
Project Creator : Abc-Arbitrage

private int WriteLine(Stream stream, byte[] messageBytes, int messageLength)
        {
            var newlineBytes = _newlineBytes;

            if (messageLength + newlineBytes.Length < messageBytes.Length)
            {
                Array.Copy(newlineBytes, 0, messageBytes, messageLength, newlineBytes.Length);
                messageLength += newlineBytes.Length;

                stream.Write(messageBytes, 0, messageLength);
                return messageLength;
            }

            stream.Write(messageBytes, 0, messageLength);
            stream.Write(newlineBytes, 0, newlineBytes.Length);
            return messageLength + newlineBytes.Length;
        }

19 View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage

public unsafe int WritePrefix(Stream stream, ILogEventHeader logEventHeader, Encoding encoding)
        {
            _stringBuffer.Clear();
            _appendMethod(this, logEventHeader);

            int bytesWritten;
            fixed (byte* buf = &_buffer[0])
                bytesWritten = _stringBuffer.CopyTo(buf, _buffer.Length, 0, _stringBuffer.Count, encoding);

            stream.Write(_buffer, 0, bytesWritten);
            return bytesWritten;
        }

19 View Source File : Ecoji.cs
License : MIT License
Project Creator : abock

public static void Decode(TextReader input, Stream output)
    {
        if (input is null)
            throw new ArgumentNullException(nameof(input));

        if (output is null)
            throw new ArgumentNullException(nameof(output));

        var inBuffer = new int[4];
        var outBuffer = new byte[5];

        while (true)
        {
            for (int i = 0; i < inBuffer.Length; i++)
            {
                int c;

                do c = input.ReadRune();
                while (c == '\n' || c == '\r');

                if (c < 0)
                {
                    if (i == 0)
                        return;

                    throw new UnexpectedEndOfInputException(
                        "number of input code points is not a multiple of 4");
                }

                inBuffer[i] = c;
            }

            var b0 = GetEmojiIndex(inBuffer[0]);
            var b1 = GetEmojiIndex(inBuffer[1]);
            var b2 = GetEmojiIndex(inBuffer[2]);
            var b3 = inBuffer[3] switch
            {
                padding40 => 0,
                padding41 => 1 << 8,
                padding42 => 2 << 8,
                padding43 => 3 <<8,
                _ => GetEmojiIndex(inBuffer[3])
            };

            outBuffer[0] = (byte)(b0 >> 2);
            outBuffer[1] = (byte)(((b0 & 0x3) << 6) | (b1 >> 4));
            outBuffer[2] = (byte)(((b1 & 0xf) << 4) | (b2 >> 6));
            outBuffer[3] = (byte)(((b2 & 0x3f) << 2) | (b3 >> 8));
            outBuffer[4] = (byte)(b3 & 0xff);

            if (inBuffer[1] == padding)
                output.Write(outBuffer, 0, 1);
            else if (inBuffer[2] == padding)
                output.Write(outBuffer, 0, 2);
            else if (inBuffer[3] == padding)
                output.Write(outBuffer, 0, 3);
            else if (inBuffer[3] == padding40 ||
                inBuffer[3] == padding41 ||
                inBuffer[3] == padding42 ||
                inBuffer[3] == padding43)
                output.Write(outBuffer, 0, 4);
            else
                output.Write(outBuffer, 0, 5);
        }

19 View Source File : Host.cs
License : MIT License
Project Creator : acandylevey

public void SendMessage(JObject data)
        {
            Log.LogMessage("Sending Message:" + JsonConvert.SerializeObject(data));

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data.ToString(Formatting.None));
            Stream stdout = Console.OpenStandardOutput();
            stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
            stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
            stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
            stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
            stdout.Write(bytes, 0, bytes.Length);
            stdout.Flush();
        }

19 View Source File : CorreiosWebservice.cs
License : MIT License
Project Creator : ACBrNet

public override ACBrEndereco[] BuscarPorCEP(string cep)
		{
			try
			{
				var request = (HttpWebRequest)WebRequest.Create(CORREIOS_URL);
				request.ProtocolVersion = HttpVersion.Version10;
				request.UserAgent = "Mozilla/4.0 (compatible; Synapse)";
				request.Method = "POST";

				var postData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
							   "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
							   "xmlns:cli=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\"> " +
							   " <soapenv:Header/>" +
							   " <soapenv:Body>" +
							   " <cli:consultaCEP>" +
							   " <cep>" + cep.OnlyNumbers() + "</cep>" +
							   " </cli:consultaCEP>" +
							   " </soapenv:Body>" +
							   " </soapenv:Envelope>";

				var byteArray = Encoding.UTF8.GetBytes(postData);
				var dataStream = request.GetRequestStream();
				dataStream.Write(byteArray, 0, byteArray.Length);
				dataStream.Close();

				string retorno;

				// ReSharper disable once replacedignNullToNotNullAttribute
				using (var stHtml = new StreamReader(request.GetResponse().GetResponseStream(), ACBrEncoding.ISO88591))
					retorno = stHtml.ReadToEnd();

				var doc = XDoreplacedent.Parse(retorno);
				var element = doc.ElementAnyNs("Envelope").ElementAnyNs("Body").ElementAnyNs("consultaCEPResponse").ElementAnyNs("return");

				var endereco = new ACBrEndereco();
				endereco.CEP = element.Element("cep").GetValue<string>();
				endereco.Bairro = element.Element("bairro").GetValue<string>();
				endereco.Municipio = element.Element("cidade").GetValue<string>();
				endereco.Complemento = $"{element.Element("complemento").GetValue<string>()}{Environment.NewLine}{element.Element("complemento2").GetValue<string>()}";
				endereco.Logradouro = element.Element("end").GetValue<string>();
				endereco.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), element.Element("uf").GetValue<string>());

				endereco.TipoLogradouro = endereco.Logradouro.Split(' ')[0];
				endereco.Logradouro = endereco.Logradouro.SafeReplace(endereco.TipoLogradouro, string.Empty);

				return new[] { endereco };
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao consulta CEP.");
			}
		}

19 View Source File : ConsultaExtensions.cs
License : MIT License
Project Creator : ACBrNet

internal static string SendPost(this HttpWebRequest request, Dictionary<string, string> postData, Encoding enconde)
        {
            request.Method = "POST";

            var post = new StringBuilder();
            var lastKey = postData.Last().Key;
            foreach (var postValue in postData)
            {
                post.Append($"{postValue.Key}={postValue.Value}");
                if (postValue.Key != lastKey) post.Append("&");
            }

            var byteArray = enconde.GetBytes(post.ToString());
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            var dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            Guard.Against<ACBrException>(responseStream == null, "Erro ao acessar o site.");

            string retorno;
            using (var stHtml = new StreamReader(responseStream, enconde))
                retorno = stHtml.ReadToEnd();

            return retorno;
        }

19 View Source File : PrimitiveMethods.Download.cs
License : MIT License
Project Creator : Accelerider

public static IObservable<(long Offset, int Bytes)> CreateBlockDownloadItem(
            Func<Task<(HttpWebResponse response, Stream inputStream)>> streamPairFactory,
            BlockTransferContext context) => Observable.Create<(long Offset, int Bytes)>(o =>
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            // Execute copy stream by async.
            Task.Run(async () =>
            {
                try
                {
                    (HttpWebResponse response, Stream outputStream) = await streamPairFactory();

                    using (response)
                    using (var inputStream = response.GetResponseStream())
                    using (outputStream)
                    {
                        byte[] buffer = new byte[128 * 1024];
                        int count;

                        Guards.ThrowIfNull(inputStream);

                        // ReSharper disable once PossibleNullReferenceException
                        while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                Debug.WriteLine($"[CANCELLED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                                o.OnError(new BlockTransferException(context, new OperationCanceledException()));
                                return;
                            }

                            outputStream.Write(buffer, 0, count);
                            o.OnNext((context.Offset, count));
                        }
                    }

                    o.OnCompleted();
                }
                catch (Exception e)
                {
                    o.OnError(new BlockTransferException(context, e));
                }
            }, cancellationToken);

            return () =>
            {
                Debug.WriteLine($"[DISPOSED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                cancellationTokenSource.Cancel();
            };
        });

See More Examples