2

I am new to C# and can not seem to find a way to do copy a text string from a textbox to a specific starting point in a byte array other than using a loop.

I know I can:

  var myBuffer = new byte[20];
  myBuffer = ASCIIEncoding.ASCII.GetBytes(textBox.Text);

but how do I start the text at an offset within the array for example at the fourth byte:

 starting at myBuffer[3], copy textBox.Text;   // Representation of what I need

Is there an elegant solution?

2 Answers 2

3

Yes, there is an elegant solution: use the five-argument overload of GetBytes method:

ASCIIEncoding.ASCII.GetBytes(textBox.Text, 0, 17, myBuffer, 3);

The first three arguments supply the string, the offset into that string from which to start encoding, and the number of characters to encode. The last two arguments supply the destination array, and the offset into it from which to start writing.

Sign up to request clarification or add additional context in comments.

1 Comment

Elegant and it works! (Just changed the length (17) to textBox.Text.Length) Thanks!
0

Use Substring like this:

var myBuffer = new byte[20];
myBuffer = ASCIIEncoding.ASCII.GetBytes(textBox.Text.Substring(3));

2 Comments

Unfortunately, that copies from the fourth character of the the textbox, but I need all of the text copied starting at the fourth byte of the array.
ASCII encoding is a single byte per character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.