Show / Hide Table of Contents

WriteString Method

WriteString(int, string, Encoding)

Add a string as the value to be written out.

C#
public void WriteString(int tag, string value, Encoding encoding)

Parameters

Type Name Description
int tag

The tag that will be written out when this TLV is encoded.

string value

The string to be converted into a byte array.

Encoding encoding

The encoding system to use to convert the string to a byte array, such as System.Text.Encoding.ASCII or UTF8.

Exceptions

Type Condition
ArgumentNullException

The encoding argument is null.

TlvException

The tag is invalid, or the length is unsupported.

Remarks

The C# String object is essentially a character array. However, each character is 16 bits. You can build strings using ASCII characters (each of which is 8 bits long, with the most significant bit 0). For example,

string someString = "ABCD"
represented internally as 00 41 00 42 00 43 00 44

But suppose you want to write out a TLV with the value being the byte array that is the ASCII character array.

 tag 04 41 42 43 44
You don't want to simply copy the internal array, otherwise you
would get
 tag 08 00 41 00 42 00 43 00 44

To get a byte array that returns each character as a single byte, you can use the System.Text.Encoding class. For the TlvWriter class, this method (WriteString) will call on the Encoding class to convert the input string into a byte array that will be the value in a TLV. You only need supply the encoding scheme. The scheme you specify must be in the form of a System.Text.Encoding object. It is easy to supply such and object, simply pass in Encoding.ASCII, Encoding.UTF8, or any of the other encoding schemes supported in that class (look at the documentation for System.Text.Encoding, there are several properties with the summary of "Gets an encoding for...").

For example:

string someString = "ABCD";
writer.WriteString(0x81, someString, Encoding.ASCII);

A string with non-ASCII characters will be stored internally with the 16-bit version of that character. For example, look at a string with the "plus-minus" character.

string someString = "A\u00B1B"; // this is A +or- B
represented internally as 00 41 00 B1 00 42
Encoding that using the ASCII encoding scheme will not produce the correct output. There are a couple of options:
writer.WriteString(tag, someString, Encoding.BigEndianUnicode);
  tag 06 00 41 00 B1 00 42
writer.WriteString(tag, someString, Encoding.UTF8);
  tag 04 41 C2 B1 42
In this article
Back to top Generated by DocFX