Question : Most Efficient Way Of Appending to a Byte[]

Hi

I am trying to build up a byte[], the data consists of a start byte followed by an xml message, followed by an end byte .

I am using the following snippet of code to append the start and end bytes to my byte[] which initially only has the xml data. I pass in the string containing the xml and return a byte[] containing the complete message.

 
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
private byte[] FormatKeyPadMessage(string xmlMessage)
        {
            try
            {
                byte[] byteMessage = new byte[4096];
                byte[] startChar = new byte[1];
                byte[] endChar = new byte[1];

                startChar[0] = 0x02;
                endChar[0] = 0x03;

                byteMessage = StrToByteArray(xmlMessage);

                int arraySize = byteMessage.Length + 3;

                var ms = new MemoryStream(new byte[arraySize], 0, arraySize, true, true);
                ms.Write(startChar, 0, 1);
                ms.Write(byteMessage, 0, byteMessage.Length);
                ms.Write(endChar, 0, 1);

                byte[] mergedMessage = ms.GetBuffer();

                return mergedMessage;
            }
            catch (Exception ex)
            {
                
                return null;
            }
        }


This works, but the functions seems to be innificient and I was wondering if their is a better way of doing this.

Any help appreciated
Regards




Answer : Most Efficient Way Of Appending to a Byte[]

Random Solutions  
 
programming4us programming4us