Encodes a set of characters from the specified string into the specified byte array.
- s
- The string containing the set of characters to encode.
- charIndex
- The index of the first character to encode.
- charCount
- The number of characters to encode.
- bytes
- The byte array to contain the resulting sequence of bytes.
- byteIndex
- The index at which to start writing the resulting sequence of bytes.
The actual number of bytes written into bytes.
Type Reason ArgumentException bytes does not contain sufficient space to store the encoded characters. ArgumentNullException s is null.
-or-
bytes is null.
ArgumentOutOfRangeException charIndex < 0.
-or-
charCount < 0.
-or-
byteIndex < 0.
-or-
charIndex and charCount do not specify a valid range in s (i.e. (charIndex + charCount) > s.Length).
-or-
byteIndex >= bytes.Length.
To calculate the exact array size required by UnicodeEncoding.GetBytes(string, int, int, Byte[], int) to store the resulting bytes, the application uses UnicodeEncoding.GetByteCount(Char[], int, int). To calculate the maximum array size, the application should use UnicodeEncoding.GetMaxByteCount(int). The UnicodeEncoding.GetByteCount(Char[], int, int) method generally allows allocation of less memory, while the UnicodeEncoding.GetMaxByteCount(int) method generally executes faster.
With error detection, an invalid sequence causes this method to throw a ArgumentException. Without error detection, invalid sequences are ignored, and no exception is thrown.
Data to be converted, such as data read from a stream, might be available only in sequential blocks. In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the System.Text.Decoder or the System.Text.Encoder provided by the UnicodeEncoding.GetDecoder method or the UnicodeEncoding.GetEncoder method, respectively.
To ensure that the encoded bytes are decoded properly, the application should prefix encoded bytes with a preamble.