Hi!

I want to join 2 strings, but it has been impossible.
I have this:

i = socket.Receive(buffer);
 recibido = System.Text.Encoding.UTF8.GetString(buffer)

Buffer contains: "C:"

I want to add the "\\" to the string so i have tried to do:

recibido = recibido + "\\".

But no way, when y print the result it shows again "C:"
I have also tried using StringBuilder:
http://msdn.microsoft.com/en-us/library/ms228504(v=vs.80).aspx

But is the same it just print "C:"

I ve also tried changing the "\\" for any other thing like "hello"... and it still shows "C:".

Dani AI

Generated

As hinted, the real issue was decoding the whole buffer instead of only the bytes that were actually received. Socket.Receive returns how many bytes were written into the buffer; the GetString overload’s two parameters are the start offset and the byte count to convert. Decoding the entire buffer can bring in leftover or NUL bytes and make appended text appear missing.

int bytesReceived = socket.Receive(buffer);
var recibido = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesReceived);
recibido += @"\";
Console.WriteLine(recibido);

Notes and practical tips:

  • Always use the return value from Receive (or Read) as the count passed to GetString so only the fresh bytes are decoded.
  • Trailing NULs or old data in a reused buffer can cause display/truncation artifacts in some viewers; decoding exactly the received bytes avoids that.
  • UTF-8 is variable-length: a single Receive call can split a multi-byte character. For robust text handling, either accumulate bytes until a full message frame is available (length prefix or delimiter), or use a Decoder (Encoding.UTF8.GetDecoder()) to preserve incomplete sequences between reads.
  • For simple text protocols over sockets, wrapping the NetworkStream with a StreamReader (with the correct Encoding) or using explicit framing often makes the code simpler and less error-prone.

This explains why saw only "C:" and why using the offset+count fixes it.

Recommended Answers

All 4 Replies

>I want to join 2 strings, but it has been impossible.

What is the size of buffer (length of buffer array)?

string str = System.Text.Encoding.UTF8.GetString(buffer,0,2) + "\\";

You were right.
The problem is that i ve benn using "System.Text.Encoding.UTF8.GetString" without the to parameters "0" and "2". For what are they ?

Please read MSDN documentation.

System.Text.Encoding.UTF8.GetString(byteArray,offset,Length)

Thanks, i searched in google before making the question but i didnt find anything.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.