Convert string to byte[]

C

Curious

I want to assign "textString" of type string to an Emelent object,
element. However, the syntaxt for the assignment is:

string string textString = "My new text";
Element element = reader.Next();

// Next I'll need to use SetTextData to set the textString to element
(syntax below). However, SetTextData method requires two parameters,
byte[], and an integer for the size of the byte[]. Anyone can advise
me on how to get byte[] and text_data_size from textString?

element.SetTextData ( byte[], text_data_size );

Thanks!
 
J

Jon Skeet [C# MVP]

Curious said:
I want to assign "textString" of type string to an Emelent object,
element. However, the syntaxt for the assignment is:

string string textString = "My new text";
Element element = reader.Next();

// Next I'll need to use SetTextData to set the textString to element
(syntax below). However, SetTextData method requires two parameters,
byte[], and an integer for the size of the byte[]. Anyone can advise
me on how to get byte[] and text_data_size from textString?

element.SetTextData ( byte[], text_data_size );

Choose a suitable encoding, and use Encoding.GetBytes.
 
C

Curious

Will the following work?

System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] myByteArray = enc.GetBytes(textString);
int text_data_size = myByteArray.GetLength(0);

What about the way "text_data_size" is derived? Thanks!
 
C

Cor Ligthert[MVP]

Curious,

I am curious, why don't you just try it, and tell us then if it is working.
That would be a nice contribution to this newsgroup for people who are only
searching in it?

Cor
 
M

Mattias Sjögren

Will the following work?

It will work in the sense that you do get a byte array with a
representation of the text. But we don't know if it's the correct
representation, if SetTextData interprets it in some way.

Also note that the ASCII chatacter set is very limited and the
conversion to it is lossy. If you convert the byte array back to a
string, you're not guaranteed to get back the same string you
originally had. If that's a problem, UTF8 may be a better choice.

int text_data_size = myByteArray.GetLength(0);

What about the way "text_data_size" is derived? Thanks!

You could just use myByteArray.Length, the result is the same.


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top