System.Text.Encoding.GetByteCount(string)

Here are the examples of the csharp api System.Text.Encoding.GetByteCount(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

534 Examples 7

19 View Source File : MainForm.cs
License : MIT License
Project Creator : azist

private void SourceBSONText_TextChanged(object sender, EventArgs e)
    {
      var bson = ((TextBox)sender).Text;
      try
      {
        var bytes = System.Text.ASCIIEncoding.ASCII.GetByteCount(bson);
        statistics.Text = STATISTICS.Args(bytes);
      }
      catch (Exception error)
      {
        statistics.Text = error.Message;
      }
    }

19 View Source File : FormUpload.cs
License : Apache License 2.0
Project Creator : berndruecker

private static void AddFormData(string boundary, Stream formDataStream, String key, object value)
        {
            var fileToUpload = value as FileParameter;
            if (fileToUpload != null)
            {
                // Add just the first part of this parameter, since we will write the file data directly to the Stream
                string header = string.Format(
                    CultureInfo.InvariantCulture,
                    "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                    boundary,
                    fileToUpload.FileName ?? key,
                    fileToUpload.FileName ?? key,
                    fileToUpload.ContentType ?? "application/octet-stream");

                formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

                // Write the file data directly to the Stream, rather than serializing it to a string.
                formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
            }
            else
            {
                string postData = string.Format(
                    CultureInfo.InvariantCulture,
                    "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                    boundary,
                    key,
                    value);
                formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
            }
        }

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public string ReadString(int length)
        {
            int bitsPerChar = encoding.GetByteCount(" ") * 8;
            return encoding.GetString(ReadBytes(bitsPerChar*length));
        }

19 View Source File : Junction.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public static void SetDestination(string path, string destination)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException(nameof(path));
            if (string.IsNullOrEmpty(destination))
                throw new ArgumentNullException(nameof(destination));

            if (!Kernel32.TryGetFileAttributes(path, out var attributes))
                throw new IOException($"The path '{path}' does not exist.");

            if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                destination = Path.GetFullPath(destination);
                string print = destination;
                destination = DestinationPrefix + destination;

                int destinationLength = Encoding.Unicode.GetByteCount(destination);
                int printLength = Encoding.Unicode.GetByteCount(print);

                var data = new ReparseDataBuffer()
                {
                    ReparseTag = ReparseTagType.MountPoint,
                    ReparseDataLength = (ushort)(4 * sizeof(ushort) + destinationLength + sizeof(char) + printLength + sizeof(char)),
                    SubsreplaceduteNameOffset = 0,
                    SubsreplaceduteNameLength = (ushort)destinationLength,
                    PrintNameOffset = (ushort)(destinationLength + sizeof(char)),
                    PrintNameLength = (ushort)printLength,
                    PathBuffer = new byte[0x3FF0]
                };

                Encoding.Unicode.GetBytes(destination, 0, destination.Length, data.PathBuffer, 0);
                Encoding.Unicode.GetBytes(print, 0, print.Length, data.PathBuffer, destinationLength + sizeof(char));

                SetReparseData(path, data);
                return;
            }

            throw new IOException($"The path '{path}' does not point to a valid directory.");
        }

19 View Source File : JsonReaderDictionary.cs
License : MIT License
Project Creator : AllocZero

public void Add(string key, TValue value)
        {
            var bytesLength = Encoding.UTF8.GetByteCount(key);
            Span<byte> buffer = stackalloc byte[bytesLength];
            Encoding.UTF8.GetBytes(key, buffer);

            var hashCode = KeysCache.GetKey(buffer);
            var targetBucket = hashCode % _bucketsLength;

            if (_count == _entries!.Length)
            {
                var newSize = KeysCache.GetPrime(_count * 2);
                Resize(newSize);
                targetBucket = hashCode % _bucketsLength;
            }

            var index = _count++;

            _entries[index].HashCode = hashCode;
            _entries[index].Next = _buckets![targetBucket];
            _entries[index].Key = Encoding.UTF8.GetBytes(key);
            _entries[index].Value = value;
            _buckets[targetBucket] = index;
        }

19 View Source File : TokenContract_Helper.cs
License : MIT License
Project Creator : AElfProject

private void replacedertValidMemo(string memo)
        {
            replacedert(memo == null || Encoding.UTF8.GetByteCount(memo) <= TokenContractConstants.MemoMaxLength,
                "Invalid memo size.");
        }

19 View Source File : FormDataHelper.cs
License : MIT License
Project Creator : backtrace-labs

internal static byte[] GetFormData(string json, List<string> attachments, string boundary)
        {
            Stream formDataStream = new MemoryStream();

            //write jsonfile to formData
            Write(formDataStream, Encoding.UTF8.GetBytes(json), "upload_file", boundary, false);

            foreach (var attachmentPath in attachments)
            {
                if(!File.Exists(attachmentPath))
                {
                    continue;
                }
                Write(formDataStream, File.ReadAllBytes(attachmentPath), "attachment_" + Path.GetFileName(attachmentPath), boundary);
            }

            // Add the end of the request.  Start with a newline
            string footer = "\r\n--" + boundary + "--\r\n";
            formDataStream.Write(_encoding.GetBytes(footer), 0, _encoding.GetByteCount(footer));

            // Dump the Stream into a byte[]
            formDataStream.Position = 0;
            byte[] formData = new byte[formDataStream.Length];
            formDataStream.Read(formData, 0, formData.Length);
            formDataStream.Close();
            return formData;
        }

19 View Source File : Logging.cs
License : MIT License
Project Creator : actions

public void Write(string message)
        {
            // lazy creation on write
            if (_pageWriter == null)
            {
                Create();
            }

            string line = $"{DateTime.UtcNow.ToString("O")} {message}";
            _pageWriter.WriteLine(line);

            _totalLines++;
            if (line.IndexOf('\n') != -1)
            {
                foreach (char c in line)
                {
                    if (c == '\n')
                    {
                        _totalLines++;
                    }
                }
            }

            _byteCount += System.Text.Encoding.UTF8.GetByteCount(line);
            if (_byteCount >= PageSize)
            {
                NewPage();
            }
        }

19 View Source File : LuaDLL.cs
License : MIT License
Project Creator : blueberryzzz

public static void lua_pushstring(IntPtr L, string str) //ҵ��ʹ��
        {
            if (str == null)
            {
                lua_pushnil(L);
            }
            else
            {
#if !THREAD_SAFE && !HOTFIX_ENABLE
                if (Encoding.UTF8.GetByteCount(str) > InternalGlobals.strBuff.Length)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(str);
                    xlua_pushlstring(L, bytes, bytes.Length);
                }
                else
                {
                    int bytes_len = Encoding.UTF8.GetBytes(str, 0, str.Length, InternalGlobals.strBuff, 0);
                    xlua_pushlstring(L, InternalGlobals.strBuff, bytes_len);
                }
#else
                var bytes = Encoding.UTF8.GetBytes(str);
                xlua_pushlstring(L, bytes, bytes.Length);
#endif
            }
        }

19 View Source File : HostTraceListener.cs
License : MIT License
Project Creator : actions

public override void Write(string message)
        {
            base.Write(message);
            if (_enablePageLog)
            {
                int messageSize = UTF8Encoding.UTF8.GetByteCount(message);
                _currentPageSize += messageSize;
            }

            Flush();
        }

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

public static string ReadNullTerminatedString(this BinaryReader reader, Encoding encoding)
        {
            var stringBuilder = new StringBuilder();
            var streamReader = new StreamReader(reader.BaseStream, encoding);

            var startOffset = reader.BaseStream.Position;

            int intChar;
            while ((intChar = streamReader.Read()) != -1)
            {
                var c = (char) intChar;
                if (c == '\0') break;
                stringBuilder.Append(c);
            }

            var result = stringBuilder.ToString();

            reader.BaseStream.Position = startOffset + encoding.GetByteCount(result + '\0');

            return result;
        }

19 View Source File : NativeStringTest.cs
License : MIT License
Project Creator : ancientproject

[Fact]
        public void AllocateTest()
        {
            var str = "foo-bar";
            var p = NativeString.Wrap(str);
            replacedert.Equal(str.Length, p.GetLen());
            replacedert.Equal(Encoding.UTF8.GetByteCount(str), p.GetBuffer().Length);
            replacedert.Equal(Encoding.UTF8, p.GetEncoding());
            replacedert.Equal(NativeString.GetHashCode(str), p.GetHashCode());
        }

19 View Source File : DiscordRPC.cs
License : GNU General Public License v3.0
Project Creator : aelariane

private IntPtr StrToPtr(string input)
            {
                if (string.IsNullOrEmpty(input))
                {
                    return IntPtr.Zero;
                }

                var convbytecnt = Encoding.UTF8.GetByteCount(input);
                var buffer = Marshal.AllocHGlobal(convbytecnt + 1);
                for (int i = 0; i < convbytecnt + 1; i++)
                {
                    Marshal.WriteByte(buffer, i, 0);
                }
                _buffers.Add(buffer);
                Marshal.Copy(Encoding.UTF8.GetBytes(input), 0, buffer, convbytecnt);
                return buffer;
            }

19 View Source File : KeyValue.cs
License : MIT License
Project Creator : Astropilot

public static string ReadNullTermString(this Stream stream, Encoding encoding)
        {
            int characterSize = encoding.GetByteCount("e");

            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    byte[] data = new byte[characterSize];
                    stream.Read(data, 0, characterSize);

                    if (encoding.GetString(data, 0, characterSize) == "\0")
                    {
                        break;
                    }

                    ms.Write(data, 0, data.Length);
                }

                return encoding.GetString(ms.ToArray());
            }
        }

19 View Source File : Amf0Writer.cs
License : MIT License
Project Creator : a1q123456

private void WriteStringBytesImpl(string str, SerializationContext context, out bool isLongString, bool marker = false, bool forceLongString = false)
        {
            var bytesNeed = 0;
            var headerLength = 0;
            var bodyLength = 0;

            bodyLength = Encoding.UTF8.GetByteCount(str);
            bytesNeed += bodyLength;

            if (bodyLength > ushort.MaxValue || forceLongString)
            {
                headerLength = Amf0CommonValues.LONG_STRING_HEADER_LENGTH;
                isLongString = true;
                if (marker)
                {
                    context.Buffer.WriteToBuffer((byte)Amf0Type.LongString);
                }

            }
            else
            {
                isLongString = false;
                headerLength = Amf0CommonValues.STRING_HEADER_LENGTH;
                if (marker)
                {
                    context.Buffer.WriteToBuffer((byte)Amf0Type.String);
                }
            }
            bytesNeed += headerLength;
            var bufferBackend = _arrayPool.Rent(bytesNeed);
            try
            {
                var buffer = bufferBackend.replacedpan(0, bytesNeed);
                if (isLongString)
                {
                    NetworkBitConverter.TryGetBytes((uint)bodyLength, buffer);
                }
                else
                {
                    var contractRet = NetworkBitConverter.TryGetBytes((ushort)bodyLength, buffer);
                    Contract.replacedert(contractRet);
                }

                Encoding.UTF8.GetBytes(str, buffer.Slice(headerLength));

                context.Buffer.WriteToBuffer(buffer);
            }
            finally
            {
                _arrayPool.Return(bufferBackend);
            }

        }

19 View Source File : Helpers.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

public static void PktFlush(this Stream response)
        {
            const string toWrite = "0000";
            response.Write(Encoding.UTF8.GetBytes(toWrite), 0, Encoding.UTF8.GetByteCount(toWrite));
        }

19 View Source File : Encoding.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public int GetByteCount(string sText)
        {
            return M_Encoding.GetByteCount(sText);
        }

19 View Source File : RequestResponseMatcher.cs
License : MIT License
Project Creator : bartschotten

public async Task MatchRequestAndReturnResponseAsync(HttpRequest httpRequest, HttpResponse httpResponseToReturn)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            var request = new Request(httpRequest);

            var response = _matchableInteractions.Select(m => m.Match(request)).Where(r => r != null).LastOrDefault();

            string stringToReturn;
            if (response != null)
            {
                httpResponseToReturn.StatusCode = response.Status;
                foreach (var header in response.Headers)
                {
                    httpResponseToReturn.Headers.Add(header.Key, new StringValues((string)header.Value));
                }
                stringToReturn = JsonConvert.SerializeObject(response.Body);
            }
            else
            {
                var errorResponse = new RequestResponseMatchingErrorResponse()
                {
                    ActualRequest = request,
                    ExpectedRequests = _matchableInteractions.Select(m => m.Interaction.Request).ToList(),
                    Message = "No matching response set up for this request."
                };
                httpResponseToReturn.StatusCode = 400;
                stringToReturn = JsonConvert.SerializeObject(errorResponse);
            }
            await httpResponseToReturn.Body.WriteAsync(Encoding.UTF8.GetBytes(stringToReturn), 0, Encoding.UTF8.GetByteCount(stringToReturn));
        }

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

public int Size(ref BssomSizeContext context, string value)
        {
            if (value == null)
                return BssomBinaryPrimitives.NullSize;

            int dataSize = UTF8Encoding.UTF8.GetByteCount(value);
            context.ContextDataSlots.PushMyStringSize(dataSize);
            return BssomBinaryPrimitives.BuildInTypeCodeSize + BssomBinaryPrimitives.VariableNumberSize((ulong)dataSize) + dataSize;
        }

19 View Source File : TeaCryptorBase.cs
License : MIT License
Project Creator : Berrysoft

public byte[] EncryptString(string data, Encoding dataEncoding, string key, Encoding keyEncoding, int round = DefaultRound)
        {
            byte[] fixedData = new byte[GetFixedDataLength(dataEncoding.GetByteCount(data))];
            int originalLength = dataEncoding.GetBytes(data, 0, data.Length, fixedData, 0);
            byte[] fixedKey;
            if (key.Length > 0)
            {
                fixedKey = new byte[16];
                keyEncoding.GetBytes(key, 0, Math.Min(16, key.Length), fixedKey, 0);
            }
            else
            {
                fixedKey = Array.Empty<byte>();
            }
            EncryptInternal(fixedData, originalLength, fixedKey, round);
            return fixedData;
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : Alkl58

public static void Check_Unicode(string file_name)
        {
            // This function checks if the provided video file has compatible unicode characters in the filename
            // Reference: codesnippets.fesslersoft.de/how-to-check-if-a-string-is-unicode-in-c-and-vb-net/
            int asciiBytesCount = Encoding.ASCII.GetByteCount(file_name);
            int unicodBytesCount = Encoding.UTF8.GetByteCount(file_name);
            if (asciiBytesCount != unicodBytesCount)
            {
                MessageBox.Show("The filename contains non unicode characters.\n\nPlease rename your file before proceeding to guarantee a successful encode!");
            }
        }

19 View Source File : DdbWriterExtensions.cs
License : MIT License
Project Creator : AllocZero

public static void WritePaginationToken(this DdbWriter writer, string paginationToken)
        {
            writer.JsonWriter.WritePropertyName("ExclusiveStartKey");
            
            writer.JsonWriter.WriteNullValue();
            // Flush to make sure our changes don't overlap with pending changes
            writer.JsonWriter.Flush();

            // Dirty hack until System.Text.Json supports writing raw json
            writer.BufferWriter.Advance(-4);
            var bytesSize = Encoding.UTF8.GetByteCount(paginationToken);

            var bytesWritten = Encoding.UTF8.GetBytes(paginationToken, writer.BufferWriter.GetSpan(bytesSize));
            writer.BufferWriter.Advance(bytesWritten);
        }

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

public void WriteString(string value)
        {
            // Optimise the case where we have enough space to write
            // the string directly to the buffer, which should be common.
            int length = Utf8Encoding.GetByteCount(value);
            WriteLength(length);
            if (limit - position >= length)
            {
                if (length == value.Length) // Must be all ASCII...
                {
                    for (int i = 0; i < length; i++)
                    {
                        buffer[position + i] = (byte)value[i];
                    }
                }
                else
                {
                    Utf8Encoding.GetBytes(value, 0, value.Length, buffer, position);
                }
                position += length;
            }
            else
            {
                byte[] bytes = Utf8Encoding.GetBytes(value);
                WriteRawBytes(bytes);
            }
        }

19 View Source File : StringConverter.cs
License : MIT License
Project Creator : AlternateLife

public static IntPtr StringToPointerUnsafe(string text)
        {
            if (text == null)
            {
                return IntPtr.Zero;
            }

            var bufferSize = Encoding.UTF8.GetByteCount(text) + 1;

            var buffer = new byte[bufferSize];
            Encoding.UTF8.GetBytes(text, 0, text.Length, buffer, 0);

            var pointer = Marshal.AllocHGlobal(bufferSize);

            Marshal.Copy(buffer, 0, pointer, bufferSize);

            return pointer;
        }

19 View Source File : PagingLoggerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void WriteAndShipLog()
        {
            CleanLogFolder();

            try
            {
                //Arrange
                using (var hc = new TestHostContext(this))
                {
                    var pagingLogger = new PagingLogger();
                    hc.SetSingleton<IJobServerQueue>(_jobServerQueue.Object);
                    pagingLogger.Initialize(hc);
                    Guid timeLineId = Guid.NewGuid();
                    Guid timeLineRecordId = Guid.NewGuid();
                    int totalBytes = PagesToWrite * PagingLogger.PageSize;
                    int bytesWritten = 0;
                    int logDataSize = System.Text.Encoding.UTF8.GetByteCount(LogData);
                    _jobServerQueue.Setup(x => x.QueueFileUpload(timeLineId, timeLineRecordId, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true))
                        .Callback((Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource) =>
                        {
                            bool fileExists = File.Exists(path);
                            replacedert.True(fileExists);

                            using (var freader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read), System.Text.Encoding.UTF8))
                            {
                                string line;
                                while ((line = freader.ReadLine()) != null)
                                {
                                    replacedert.EndsWith(LogData, line);
                                    bytesWritten += logDataSize;
                                }
                            }
                            File.Delete(path);
                        });

                    //Act
                    int bytesSent = 0;
                    pagingLogger.Setup(timeLineId, timeLineRecordId);
                    while (bytesSent < totalBytes)
                    {
                        pagingLogger.Write(LogData);
                        bytesSent += logDataSize;
                    }
                    pagingLogger.End();

                    //replacedert
                    _jobServerQueue.Verify(x => x.QueueFileUpload(timeLineId, timeLineRecordId, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true), Times.AtLeast(PagesToWrite));
                    replacedert.Equal(bytesSent, bytesWritten);
                }
            }
            finally
            {
                //cleanup
                CleanLogFolder();
            }
        }

19 View Source File : BinarySerializer.cs
License : MIT License
Project Creator : ansel86castro

private unsafe void WriteString(Stream stream, string value)
        {                       
            var bytesCount = _encoding.GetByteCount(value);
           
            WriteLenght(stream, bytesCount, Types.TYPE_STRING_8, Types.TYPE_STRING_16, Types.TYPE_STRING_32);

            if(bytesCount <= _buffer.Length)
            {
                var numBytes =_encoding.GetBytes(value, 0, value.Length, _buffer, 0);
                stream.Write(_buffer, 0, numBytes);
            }
            else
            {
                var chars = value.replacedpan();
                var bytes = _memory.Span;

                int loops = (bytesCount / _buffer.Length) + (bytesCount % _buffer.Length > 0 ? 1 : 0);
                            
                int totalChars = 0;
                for (int i = 0; i < loops; i++)
                {
                    _encoder.Convert(chars.Slice(totalChars), bytes, i == (loops - 1), out var charsUsed, out var bytesWritten, out var completed);

                    stream.Write(bytes.Slice(0, bytesWritten));
                    totalChars += charsUsed;

                    if (completed)
                        break;
                }   
            }                      
        }

19 View Source File : NatsBufferWriterExtensions.cs
License : MIT License
Project Creator : AndyPook

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static void WriteString<T>(ref this BufferWriter<T> buffer, string text)
             where T : IBufferWriter<byte>
        {
            if (string.IsNullOrEmpty(text))
                return;

            var textLength = Encoding.UTF8.GetByteCount(text);
            var textSpan = buffer.GetSpan(textLength);
            Encoding.UTF8.GetBytes(text, textSpan);
            buffer.Advance(textLength);
        }

19 View Source File : POGenerator.cs
License : MIT License
Project Creator : adams85

public void Generate(TextWriter writer, POCatalog catalog)
        {
            if (writer == null)
                throw new ArgumentNullException(nameof(writer));

            if (catalog == null)
                throw new ArgumentNullException(nameof(catalog));

            if (!HasFlags(Flags.IgnoreEncoding))
            {
                if (writer.Encoding.GetByteCount(" ") > 1)
                    throw new ArgumentException(Resources.EncodingNotSingleByte, nameof(writer));

                if (catalog.Encoding == null || Encoding.GetEncoding(catalog.Encoding).WebName != writer.Encoding.WebName)
                    throw new ArgumentException(Resources.EncodingMismatch, nameof(writer));
            }

            _writer = writer;
            _catalog = catalog;

            _stringBreak = "\"" + _writer.NewLine + "\"";
            _lineStartIndex = 0;

            try
            {
                WriteEntry(CreateHeaderEntry(), _ => { });

                for (int i = 0, n = catalog.Count; i < n; i++)
                    WriteEntry(catalog[i], w => w.WriteLine());
            }
            finally
            {
                _builder.Clear();
                if (_builder.Capacity > 1024)
                    _builder.Capacity = 1024;
            }
        }

19 View Source File : File_Data.cs
License : MIT License
Project Creator : Arefu

protected int GetStringSize(string str, Encoding encoding)
        {
            return encoding.GetByteCount((str ?? string.Empty) + '\0');
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WriteStringBytesImpl<T>(string value, SerializationContext context, List<T> referenceTable)
        {
            if (value is T tValue)
            {
                var refIndex = referenceTable.IndexOf(tValue);
                if (refIndex >= 0)
                {
                    var header = (uint)refIndex << 1;
                    WriteU29BytesImpl(header, context);
                    return;
                }
                else
                {
                    var byteCount = (uint)Encoding.UTF8.GetByteCount(value);
                    var header = (byteCount << 1) | 0x01;
                    WriteU29BytesImpl(header, context);
                    var backend = _arrayPool.Rent((int)byteCount);
                    try
                    {
                        Encoding.UTF8.GetBytes(value, backend);
                        context.Buffer.WriteToBuffer(backend.replacedpan(0, (int)byteCount));
                    }
                    finally
                    {
                        _arrayPool.Return(backend);
                    }

                    if (value.Any())
                    {
                        referenceTable.Add(tValue);
                    }
                }
            }
            else
            {
                Contract.replacedert(false);
            }
        }

19 View Source File : Hashing.cs
License : MIT License
Project Creator : aspnet

public static byte[] CreateMD5(string preplacedword, string username, byte[] salt)
        {
            using (var md5 = MD5.Create())
            {
                var preplacedwordBytes = PG.UTF8.GetBytes(preplacedword);
                var usernameBytes = PG.UTF8.GetBytes(username);

                var buffer = new byte[preplacedwordBytes.Length + usernameBytes.Length];

                preplacedwordBytes.CopyTo(buffer, 0);
                usernameBytes.CopyTo(buffer, preplacedwordBytes.Length);

                var hash = md5.ComputeHash(buffer);

                var stringBuilder = new StringBuilder();

                for (var i = 0; i < hash.Length; i++)
                {
                    stringBuilder.Append(hash[i].ToString("x2"));
                }

                var preHashBytes = PG.UTF8.GetBytes(stringBuilder.ToString());

                buffer = new byte[preHashBytes.Length + 4];

                Array.Copy(salt, 0, buffer, preHashBytes.Length, 4);

                preHashBytes.CopyTo(buffer, 0);

                stringBuilder = new StringBuilder("md5");

                hash = md5.ComputeHash(buffer);

                for (var i = 0; i < hash.Length; i++)
                {
                    stringBuilder.Append(hash[i].ToString("x2"));
                }

                var resultString = stringBuilder.ToString();
                var resultBytes = new byte[Encoding.UTF8.GetByteCount(resultString) + 1];

                Encoding.UTF8.GetBytes(resultString, 0, resultString.Length, resultBytes, 0);

                resultBytes[resultBytes.Length - 1] = 0;

                return resultBytes;
            }
        }

19 View Source File : EconomicContract.cs
License : MIT License
Project Creator : AElfProject

private void replacedertValidMemo(string memo)
        {
            replacedert(Encoding.UTF8.GetByteCount(memo) <= EconomicContractConstants.MemoMaxLength, "Invalid memo size.");
        }

19 View Source File : KeyValue.cs
License : MIT License
Project Creator : Astropilot

public static void WriteNullTermString(this Stream stream, string value, Encoding encoding)
        {
            var dataLength = encoding.GetByteCount(value);
            var data = new byte[dataLength + 1];
            encoding.GetBytes(value, 0, value.Length, data, 0);
            data[dataLength] = 0x00; // '\0'

            stream.Write(data, 0, data.Length);
        }

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

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static unsafe void WriteStringWithNotPredictingLength(IBssomBufferWriter writer, string value, long writeBackExactStringCountQuanreplacedyPos)
        {
            DEBUG.replacedert(value != null);

            int len = UTF8Encoding.UTF8.GetByteCount(value);
            writer.Seek(writeBackExactStringCountQuanreplacedyPos, BssomSeekOrgin.Begin);//Simulate StringSize, consistent with WriteString behavior
            WriteBackFixNumber(writer, (uint)len);
            ref byte refb = ref writer.GetRef(len);
            fixed (char* pValue = value)
            fixed (byte* pRefb = &refb)
            {
                UTF8Encoding.UTF8.GetBytes(pValue, value.Length, pRefb, len);
            }
            writer.Advance(len);
        }

19 View Source File : Helpers.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

public static void PktWrite(this Stream response, string input, params object[] args)
        {
            input = string.Format(input, args);
            var toWrite = (input.Length + 4).ToString("x").PadLeft(4, '0') + input;
            response.Write(Encoding.UTF8.GetBytes(toWrite), 0, Encoding.UTF8.GetByteCount(toWrite));
        }

19 View Source File : DispoIntPtr.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static DispoIntPtr AllocString(string str, out int byteCount)
        {
            byteCount = Encoding.ASCII.GetByteCount(str);
            return new DispoIntPtr(Marshal.StringToHGlobalAnsi(str));
        }

19 View Source File : X11Client.cs
License : MIT License
Project Creator : azyobuzin

internal static int GetByteCountForString8(string s)
        {
            return Encoding.UTF8.GetByteCount(s);
        }

19 View Source File : HtmlClipboard.cs
License : MIT License
Project Creator : Abdesol

public static void SetHtml(DataObject dataObject, string htmlFragment)
		{
			if (dataObject == null)
				throw new ArgumentNullException("dataObject");
			if (htmlFragment == null)
				throw new ArgumentNullException("htmlFragment");

			string htmlStart = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">" + Environment.NewLine
				+ "<HTML>" + Environment.NewLine
				+ "<BODY>" + Environment.NewLine
				+ "<!--StartFragment-->" + Environment.NewLine;
			string htmlEnd = "<!--EndFragment-->" + Environment.NewLine + "</BODY>" + Environment.NewLine + "</HTML>" + Environment.NewLine;
			string dummyHeader = BuildHeader(0, 0, 0, 0);
			// the offsets are stored as UTF-8 bytes (see CF_HTML doreplacedentation)
			int startHTML = dummyHeader.Length;
			int startFragment = startHTML + htmlStart.Length;
			int endFragment = startFragment + Encoding.UTF8.GetByteCount(htmlFragment);
			int endHTML = endFragment + htmlEnd.Length;
			string cf_html = BuildHeader(startHTML, endHTML, startFragment, endFragment) + htmlStart + htmlFragment + htmlEnd;
			Debug.WriteLine(cf_html);
			dataObject.SetText(cf_html, TextDataFormat.Html);
		}

19 View Source File : FormDataHelper.cs
License : MIT License
Project Creator : backtrace-labs

private static void Write(Stream formDataStream, byte[] data, string name, string boundary, bool clrf = true)
        {
            // Add a CRLF to allow multiple parameters to be added.
            if (clrf)
            {
                formDataStream.Write(_encoding.GetBytes("\r\n"), 0, _encoding.GetByteCount("\r\n"));
            }
            string fileHeader = $"--{boundary}\r\nContent-Disposition: form-data;" +
                $" name=\"{name}\"; filename=\"{name}\"\r\n" +
                $"Content-Type: application/octet-stream\r\n\r\n";

            formDataStream.Write(_encoding.GetBytes(fileHeader), 0, _encoding.GetByteCount(fileHeader));

            // Write the file data directly to the Stream, rather than serializing it to a string.
            formDataStream.Write(data, 0, data.Length);
        }

19 View Source File : BsonBinaryWriter.cs
License : MIT License
Project Creator : akaskela

private int CalculateSize(BsonToken t)
        {
            switch (t.Type)
            {
                case BsonType.Object:
                {
                    BsonObject value = (BsonObject)t;

                    int bases = 4;
                    foreach (BsonProperty p in value)
                    {
                        int size = 1;
                        size += CalculateSize(p.Name);
                        size += CalculateSize(p.Value);

                        bases += size;
                    }
                    bases += 1;
                    value.CalculatedSize = bases;
                    return bases;
                }
                case BsonType.Array:
                {
                    BsonArray value = (BsonArray)t;

                    int size = 4;
                    ulong index = 0;
                    foreach (BsonToken c in value)
                    {
                        size += 1;
                        size += CalculateSize(MathUtils.IntLength(index));
                        size += CalculateSize(c);
                        index++;
                    }
                    size += 1;
                    value.CalculatedSize = size;

                    return value.CalculatedSize;
                }
                case BsonType.Integer:
                    return 4;
                case BsonType.Long:
                    return 8;
                case BsonType.Number:
                    return 8;
                case BsonType.String:
                {
                    BsonString value = (BsonString)t;
                    string s = (string)value.Value;
                    value.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0;
                    value.CalculatedSize = CalculateSizeWithLength(value.ByteCount, value.IncludeLength);

                    return value.CalculatedSize;
                }
                case BsonType.Boolean:
                    return 1;
                case BsonType.Null:
                case BsonType.Undefined:
                    return 0;
                case BsonType.Date:
                    return 8;
                case BsonType.Binary:
                {
                    BsonBinary value = (BsonBinary)t;

                    byte[] data = (byte[])value.Value;
                    value.CalculatedSize = 4 + 1 + data.Length;

                    return value.CalculatedSize;
                }
                case BsonType.Oid:
                    return 12;
                case BsonType.Regex:
                {
                    BsonRegex value = (BsonRegex)t;
                    int size = 0;
                    size += CalculateSize(value.Pattern);
                    size += CalculateSize(value.Options);
                    value.CalculatedSize = size;

                    return value.CalculatedSize;
                }
                default:
                    throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
            }
        }

19 View Source File : TurnSignal_Prefs_Handler.cs
License : MIT License
Project Creator : benotter

public bool SteamSave() 
    {
        if(SteamManager.Initialized && SteamRemoteStorage.IsCloudEnabledForAccount())
        {
            string text = JsonUtility.ToJson(prefs, true);
            
            var bytes = System.Text.Encoding.ASCII.GetBytes(text);
            var byteCount = System.Text.Encoding.ASCII.GetByteCount(text);

            Debug.Log("Writing Prefs to SteamCloud!");
            return SteamRemoteStorage.FileWrite(_fileName, bytes, byteCount);
        }
        else
            return false;
    }

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

private static void SendMessage(NamedPipeServerStream stream, string message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            int messageLength = Encoding.UTF8.GetByteCount(message);

            byte[] messageBytes = new byte[sizeof(int) + messageLength];

            messageBytes[0] = (byte)(messageLength & 0xff);
            messageBytes[1] = (byte)((messageLength >> 8) & 0xff);
            messageBytes[2] = (byte)((messageLength >> 16) & 0xff);
            messageBytes[3] = (byte)((messageLength >> 24) & 0xff);
            Encoding.UTF8.GetBytes(message, 0, message.Length, messageBytes, 4);

            stream.Write(messageBytes, 0, messageBytes.Length);
        }

19 View Source File : FormUpload.cs
License : Apache License 2.0
Project Creator : berndruecker

private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
        {
            Stream formDataStream = new System.IO.MemoryStream();

            // Thanks to feedback from commenter's, add a CRLF to allow multiple parameters to be added.
            // Skip it on the first parameter, add it to subsequent parameters.
            bool needsCLRF = false;

            foreach (var param in postParameters)
            {
                if (param.Value is List<object>)
                {
                    // list of files
                    foreach (var value in (List<object>)param.Value)
                    {
                        if (needsCLRF)
                            formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
                        AddFormData(boundary, formDataStream, param.Key, value);
                        needsCLRF = true;
                    }
                }
                else
                {
                    // only a single file
                    if (needsCLRF)
                        formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));

                    AddFormData(boundary, formDataStream, param.Key, param.Value);
                    needsCLRF = true;
                }
            }

            // Add the end of the request.  Start with a newline
            string footer = "\r\n--" + boundary + "--\r\n";
            formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));

            // Dump the Stream into a byte[]
            formDataStream.Position = 0;
            byte[] formData = new byte[formDataStream.Length];
            formDataStream.Read(formData, 0, formData.Length);
            formDataStream.Close();

            formDataStream.Dispose();

            return formData;
        }

19 View Source File : MKMInteract.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
      {
        // throw the exception ourselves to prevent sending requests to MKM that would end with this error 
        // because MKM tends to revoke the user's app token if it gets too many requests above the limit
        // the 429 code is the same MKM uses for this error
        if (denyAdditionalRequests)
        {
          // MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
          // the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
          if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
            throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
          else
            denyAdditionalRequests = false;
        }
        // enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
        // can arrive to MKM with some delay, but it should be close enough
        var now = DateTime.Now;
        while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
        {
          requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
        }
        if (requestTimes.Count >= maxRequestsPerMinute)
        {
          // wait until 60.01 seconds preplaceded since the oldest request
          // we know (now - peek) is <= 60, otherwise it would get dequeued above,
          // so we are preplaceding a positive number to sleep
          System.Threading.Thread.Sleep(
              60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
          requestTimes.Dequeue();
        }

        requestTimes.Enqueue(DateTime.Now);
        XmlDoreplacedent doc = new XmlDoreplacedent();
        for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
        {
          try
          {
            var request = WebRequest.CreateHttp(url);
            request.Method = method;

            request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
            request.Method = method;

            if (body != null)
            {
              request.ServicePoint.Expect100Continue = false;
              request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
              request.ContentType = "text/xml";

              var writer = new StreamWriter(request.GetRequestStream());

              writer.Write(body);
              writer.Close();
            }

            var response = request.GetResponse() as HttpWebResponse;

            // just for checking EoF, it is not accessible directly from the Stream object
            // Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets). 
            // Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser 
            // even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
            StreamReader s = new StreamReader(response.GetResponseStream());
            if (!s.EndOfStream)
              doc.Load(s);
            s.Close();
            int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
            int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
            if (requestCount >= requestLimit)
            {
              denyAdditionalRequests = true;
              denyTime = DateTime.UtcNow;
            }
            MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
            break;
          }
          catch (WebException webEx)
          {
            // timeout can be either on our side (Timeout) or on server
            bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
            if (webEx.Status == WebExceptionStatus.ProtocolError)
            {
              if (webEx.Response is HttpWebResponse response)
              {
                isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
                    || response.StatusCode == HttpStatusCode.ServiceUnavailable;
              }
            }
            // handle only timeouts, client handles other exceptions
            if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
              System.Threading.Thread.Sleep(1500); // wait and try again
            else
              throw webEx;
          }
        }
        return doc;
      }

19 View Source File : HostTraceListener.cs
License : MIT License
Project Creator : actions

public override void WriteLine(string message)
        {
            base.WriteLine(message);
            if (_enablePageLog)
            {
                int messageSize = UTF8Encoding.UTF8.GetByteCount(message);
                _currentPageSize += messageSize;
                if (_currentPageSize > _pageSizeLimit)
                {
                    Flush();
                    if (Writer != null)
                    {
                        Writer.Dispose();
                        Writer = null;
                    }

                    Writer = CreatePageLogWriter();
                    _currentPageSize = 0;
                }
            }

            Flush();
        }

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

public ulong GetSize()
        {
            return (ulong)Encoding.UTF8.GetByteCount(this.Value) + 1;
        }

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

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int StringSize(string value)
        {
            int size = UTF8Encoding.UTF8.GetByteCount(value);
            return FixNumberSize((ulong)UTF8Encoding.UTF8.GetMaxByteCount(value.Length)) + size;
        }

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

public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
            {
                cookieContainer = cookieContainer ?? new CookieContainer();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                request.CookieContainer = cookieContainer;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(postDataStr);
                myStreamWriter.Close();

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

                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 View Source File : StringConstant.cs
License : MIT License
Project Creator : adamant

public static int GetByteLength(string value)
        {
            return Encoding.GetByteCount(value);
        }

19 View Source File : Lump.cs
License : GNU General Public License v3.0
Project Creator : anotak

public static byte[] MakeFixedName(string name, Encoding encoding)
		{
			// Make uppercase name and count bytes
			string uppername = name.Trim().ToUpper();
			int bytes = encoding.GetByteCount(uppername);
			if(bytes < 8) bytes = 8;
			
			// Make 8 bytes, all zeros
			byte[] fixedname = new byte[bytes];

			// Write the name in bytes
			encoding.GetBytes(uppername, 0, uppername.Length, fixedname, 0);

			// Return result
			return fixedname;
		}

See More Examples