0

How to get string from this code instead of array of char ?

Client Code :

            stm = tcpClient.GetStream() 
            Dim ascenc As New ASCIIEncoding
            Dim byteData() As Byte = ascenc.GetBytes(strMessage(counter))
            Thread.Sleep(2000)
            Console.WriteLine("Transmitted ")
            stm.Write(byteData, 0, byteData.Length())

Server code :

Dim size As Integer = TcpSocket.Receive(bitData)
            Dim chars(size) As Char
            For i As Integer = 0 To size
                chars(i) = Convert.ToChar(bitData(i)) // i want to get the string directly, how ?
            Next
            Dim newString As New String(chars)
            Console.WriteLine(newString)
            strMessage(counter) = newString
  • [Tried](https://msdn.microsoft.com/en-us/library/ms172827.aspx) [googling](https://www.dotnetperls.com/convert-string-byte-array-vbnet) [at](http://stackoverflow.com/questions/1003275/how-to-convert-byte-to-string) [all?](http://www.convertdatatypes.com/Convert-Byte-Array-to-String-in-VB.net.html) – A Friend Apr 10 '17 at 08:51

2 Answers2

1

You already have it implemented with your code I suggested:

Dim MyString As String = New String(MyArray)

If you want to convert the byte array you can use:

Dim MyString As String = Encoding.ASCII.GetString(bytes)
Mederic
  • 1,949
  • 4
  • 19
  • 36
  • He's already doing that, though: `Dim newString As New String(chars)`. He wants to convert the byte array instead, rather than having to iterate it to create a char array. – Visual Vincent Apr 10 '17 at 08:55
  • @VisualVincent Yeah thats why I edited i don't understand his problem. Then a simple: Encoding.ASCII.GetString(bytes) – Mederic Apr 10 '17 at 08:56
  • That is what he wants, yes. I wrote so in my answer (except I used his method rather than the static property). – Visual Vincent Apr 10 '17 at 08:58
  • @VisualVincent Oh the page didn't refresh and I didn't see it. Upvote for the nice structure. – Mederic Apr 10 '17 at 08:59
1

You can use ASCIIEncoding on the server as well. Just use its GetString() method rather than GetBytes().

Dim ascenc As New ASCIIEncoding
Dim newString As String = ascenc.GetString(bitData)
Visual Vincent
  • 18,045
  • 5
  • 28
  • 75