4

I'm using PowerShell to write messages to a message queue, which has a message size limit on it. Before writing a message to the queue, I need to know how many bytes a string is.

How can I figure out how many bytes the string is, so I can perform a size comparison, before writing to the queue?

1 Answer 1

10

The answer to this depends on the text encoding you're using.

You can use the static method GetByteCount() on a few different text encodings. Assuming you're using UTF-8 text encoding, you can reference the UTF8 static property on the System.Text.Encoding class, to obtain a reference to the UTF8Encoding class.

Here's an example, where we retrieve a System.Diagnostics.Process object, convert it to a JSON representation, and then determine how many bytes it uses, given a UTF8 encoding.

$Process = Get-Process -Name System | ConvertTo-Json
[System.Text.Encoding]::UTF8.GetByteCount($Process)

Here's the same example, but changing the text encoding to ASCII.

[System.Text.Encoding]::ASCII.GetByteCount($Process)

If your input string doesn't contain any Unicode characters, you should get the same result for both ASCII and UTF-8 byte counts.

NOTE: The System.Text.Encoding base class declares a virtual method named GetByteCount(), however it's up to the child classes (eg. UTF8Encoding) to actually implement this method.

https://msdn.microsoft.com/en-us/library/w3739zdy(v=vs.110).aspx

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

1 Comment

Yes, so, what is the encoding that you're using in the message? Both the sender and receivers have to know and use it. ("UTF-8 characters": UTF-8 is an encoding for the Unicode characters set, as is UTF-16, which is the encoding for the String and datatype. So, all of your characters are Unicode.)

Your Answer

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