This method converts a Unicode string to its UTF-8 encoded representation.
The result is returned as a byte array which can be written to a file,
transmitted over a network connection, or passed to another system that
expects UTF-8 encoded input.
In Visual Basic, this method is typically used to convert the contents of
a String variable into a Byte() array. This is useful
when interacting with APIs, services, or file formats that require text to be
encoded in UTF-8 rather than stored using the internal UTF-16 representation
used by the Visual Basic runtime.
If the input string is empty, the method returns an empty array. If the
input contains only ASCII characters (U+0000 to U+007F), the returned array
will be identical to the original characters in the string, but represented
as UTF-8 bytes.
This method ensures that the UTF-8 encoding is strictly valid and does
not emit a byte order mark (BOM) at the beginning of the array. To verify
that the returned array contains valid UTF-8, you can use the
IsValidUtf8 method.
To verify that the UTF-8 conversion was successful and lossless, you can
use the Utf8ToStr method to convert the byte array back to a string and
compare it with the original. This is particularly useful in test scenarios
where you want to ensure that encoding and decoding operations preserve all
characters without introducing errors or data loss.
The StrConv function in Visual Basic 6.0 and VBScript does
not support UTF-8 encoding or decoding. Attempting to use
StrConv(..., vbFromUnicode) or StrConv(..., vbUnicode)
to convert between strings and UTF-8 byte arrays will produce
incorrect results or replace characters with question marks. Always
use StrToUtf8 and Utf8ToStr when working with UTF-8
encoded text.
The StrToUtf8 and Utf8ToStr methods are provided
specifically for use with the ActiveX control in environments such as
Visual Basic 6.0 or scripting languages like VBScript, which do not
include built-in support for UTF-8 text encoding. In the .NET version
of the FileEncoder class, these methods are not included
because the .NET Framework and .NET Core provide native support for
UTF-8 conversion through the System.Text.Encoding classes.
Developers using .NET can convert between strings and UTF-8 byte arrays
using Encoding.UTF8.GetBytes and Encoding.UTF8.GetString,
making these methods unnecessary in managed code environments.