C # Equivalent to VB6 'StrConv'

I want to convert a string to an array of bytes. (Yes) I saw several questions already asked on this topic, but I did not find the answers too useful. In most cases, the questions were rather inadequate. I am doing some research and I will post my results below.

I found all these methods for converting a string to an array of bytes in C # .net. Many of them were encoded by themselves.

1)

private byte[] getByte(string s)
          {
                 Byte[] b = new byte[s.Length];

                 for (int i = 0; i < s.Length; i++)
                 {
                       char c = Convert.ToChar(s.Substring(i, 1));
                       b[i] = Convert.ToByte(c);
                 }
                 return b;
          }

2)

System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
        Byte[] bytes = encoding.GetBytes(yourString)

3) ** Of course, there is a file.ReadAllBytes method, but I do not read this data from a file.

So, does anyone know about C # equivalent to the following (this is VB6)?

Dim sData as string
Dim b() as byte
sData = "Test String in VB6"
b() = strconv(sData, VbFromUnicode)

Many thanks. I look forward to some wonderful answers!

+3
source share
3 answers
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
+5
source

Your option 2 is almost absent, you just need to change the encoder

System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
byte[] unicodeStringAsBytes = UTF8.GetBytes(myString);
+5
source

to try

return System.Text.Encoding.UTF8.GetBytes(yourString);
+1
source

All Articles