[英]How to append a control character to a string in c#?
I see similar answers here but none are what I need. 我在这里看到了类似的答案,但我都不需要。
I am trying to build a socket acknowledgement where the string message starts with a 0B
control character and has both a hex 1C
and a hex 0D
at the end of the transaction. 我试图建立一个套接字确认,其中字符串消息以0B
控制字符开头,并且在事务结束时同时具有十六进制1C
和十六进制0D
。
StringBuilder sb = new StringBuilder();
char b = '\u000b';
char c = '\u001c';
char d = '\u000d';
sb.Append(b);
sb.AppendLine(ackMessage);
sb.Append("MSA|AA|" + controlID);
sb.Append(c);
sb.Append(d);
string myMessage = sb.ToString();
The receiver of the message is not seeing the control characters at the beginning and end of the block, and I'm not sure where I am coding wrong. 消息的接收者在块的开头和结尾都看不到控制字符,而且我不确定我在哪里编码错误。 Any help would be greatly appreciated. 任何帮助将不胜感激。 I don't know how to copy the code here in proper format so please forgive the formatting of this question ;) 我不知道如何以正确的格式在此处复制代码,因此请原谅此问题的格式;)
Thanks. 谢谢。
Greg 格雷格
Strings and chars in .NET are Unicode. .NET中的字符串和字符是Unicode。 Is your consumer expecting Unicode? 您的消费者期望使用Unicode吗? Maybe you need to create / pass a ASCII byte array instead? 也许您需要创建/传递ASCII字节数组呢?
byte[] unicodeBytes = Encoding.Unicode.GetBytes(ackMessage);
var asciiBytes = new List<byte>(ackMessage.Length + 3);
asciiBytes.Add(0x0b);
asciiBytes.AddRange(Encoding.Convert(Encoding.Unicode, Encoding.ASCII, unicodeBytes));
asciiBytes.AddRange(new byte[] { 0x1c, 0x0d });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.