Reputation: 759
in a C# code, I'm converting a string (example PRmlyc3RuYW1lOj1FbW1hbnVlbMKkJMKkTGFzdE5hbWU6PURyZXV4wqQkwqRNYWlsYm94VHlwZTo9TWJ4
) to a byte array and then from a powershell script converting back the byte array to a string.
This results in garbage in the beginning and end of the string:
☺ ????☺ ♠☺ PRmlyc3RuYW1lOj1FbW1hbnVlbMKkJMKkTGFzdE5hbWU6PURyZXV4wqQkwqRNYWlsYm94VHlwZTo9TWJ4♂
C# code :
byte[] array = ToByteArray(encodedParameters);
private byte[] ToByteArray(object source)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
return stream.ToArray();
}
}
Powershell decoding:
$cmd = [System.Text.Encoding]::ASCII.GetString($buf, 0, $len)
or
$cmd = [System.Text.Encoding]::UTF8.GetString($buf, 0, $len)
or
$cmd = [System.Text.Encoding]::UNICODE.GetString($buf, 0, $len)
If I dump the byte array in C# and in powershell, I'm getting the same buffer:
0 1 0 0 0 255 255 255 255 1 0 0 0 0 0 0 0 6 1 0 0 0 80 82 109 108 121 99 51 82 117 89 87 49 108 79 106 49 70 98 87 49 104 98 110 86 108 7 84 71 70 122 100 69 53 104 98 87 85 54 80 85 82 121 90 88 86 52 119 113 81 107 119 113 82 78 89 87 108 115 89 109 57 52 86 72 108 119 11
The characters in bold seam to be extra bytes added by C#, a kind of header and ending character.
Question: how can I get the string back in powershell without this extra garbage?
Upvotes: 2
Views: 2583
Reputation: 16792
The C# is doing a binary serialization of the .NET object. That will include both the "raw data" of the object (e.g. the characters of a string, fields of other objects) plus some extra goo that includes the type info.
The powershell is not deserializing a .NET object, it is trying to decode an encoded string. Encoding is not the same as serializing, so Encoding.ASCII.GetString
doesn't quite work.
So you have 2 options:
BinaryFormatter.Deserialize
in powershell to deserialize a byte array to a stringEncoding.ASCII.GetBytes
in C# to encode a string to a byte arrayUpvotes: 5
Reputation: 39013
That's because you're serializing the array in C# but decoding it in Powershell. You need to encode the string in C#, then decoding in Powershell will work.
Or, you can deserialize in Powershell, but it's a bit strange - encoding and decoding makes more sense.
By the way, why can't you just pass a string?
Upvotes: 0