473,671 Members | 2,588 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting a MemoryStream of bytes to a string

Sounds an easy task and should be, but the code result is a blank byte
array.

Comments within code.

The code is:

Stream sr = new MemoryStream();
XmlSerializer s = new XmlSerializer(t ypeof(CRM.Busin essEntity));
s.Serialize(sr, response.Busine ssEntity);

//MemoryStream does contain correct byte array after the above.

byte[] serBuf = new byte[(int)sr.Length - 1];
sr.Read(serBuf, 0, serBuf.Length - 1);
sr.Close(); //Close the stream to release the memory.

//At this point serBuf is never set with the byte array held in the
MemoryStream!

//Now we want to convert the array of bytes to a string.
//We do this by using the Encoding class.
string myData = System.Text.Enc oding.ASCII.Get String(serBuf);
Any help would be great.
Simon.
May 23 '06 #1
3 18067
If you want to serialize to string try this:

StringBuilder sb = new StringBuilder() ;
XmlSerializer ser = new XmlSerializer(t ypeof(CRM.Busin essEntity));
using(StringWri ter sw = new StringWriter(sb ))
{
ser.Serialize(s w, job);
return sb.ToString();
}

Ollie Riches

"Simon Hart" <srhartone[no spam]@yahoo.com> wrote in message
news:%2******** *******@TK2MSFT NGP02.phx.gbl.. .
Sounds an easy task and should be, but the code result is a blank byte
array.

Comments within code.

The code is:

Stream sr = new MemoryStream();
XmlSerializer s = new XmlSerializer(t ypeof(CRM.Busin essEntity));
s.Serialize(sr, response.Busine ssEntity);

//MemoryStream does contain correct byte array after the above.

byte[] serBuf = new byte[(int)sr.Length - 1];
sr.Read(serBuf, 0, serBuf.Length - 1);
sr.Close(); //Close the stream to release the memory.

//At this point serBuf is never set with the byte array held in the
MemoryStream!

//Now we want to convert the array of bytes to a string.
//We do this by using the Encoding class.
string myData = System.Text.Enc oding.ASCII.Get String(serBuf);
Any help would be great.
Simon.

May 23 '06 #2
Ollie,

Thank you, simplified and works a treat.

Cheers
Simon.

"Ollie Riches" <ol**********@p honeanalyser.ne t> wrote in message
news:u6******** ******@TK2MSFTN GP02.phx.gbl...
If you want to serialize to string try this:

StringBuilder sb = new StringBuilder() ;
XmlSerializer ser = new XmlSerializer(t ypeof(CRM.Busin essEntity));
using(StringWri ter sw = new StringWriter(sb ))
{
ser.Serialize(s w, job);
return sb.ToString();
}

Ollie Riches

"Simon Hart" <srhartone[no spam]@yahoo.com> wrote in message
news:%2******** *******@TK2MSFT NGP02.phx.gbl.. .
Sounds an easy task and should be, but the code result is a blank byte
array.

Comments within code.

The code is:

Stream sr = new MemoryStream();
XmlSerializer s = new XmlSerializer(t ypeof(CRM.Busin essEntity));
s.Serialize(sr, response.Busine ssEntity);

//MemoryStream does contain correct byte array after the above.

byte[] serBuf = new byte[(int)sr.Length - 1];
sr.Read(serBuf, 0, serBuf.Length - 1);
sr.Close(); //Close the stream to release the memory.

//At this point serBuf is never set with the byte array held in the
MemoryStream!

//Now we want to convert the array of bytes to a string.
//We do this by using the Encoding class.
string myData = System.Text.Enc oding.ASCII.Get String(serBuf);
Any help would be great.
Simon.


May 23 '06 #3
<"Simon Hart" <srhartone[no spam]@yahoo.com>> wrote:

<snip>

Leaving aside the rest of your question, this bit is very, very dodgy:
//Now we want to convert the array of bytes to a string.
//We do this by using the Encoding class.
string myData = System.Text.Enc oding.ASCII.Get String(serBuf);


If there are any non-ASCII characters in the XML, you will lose data.
You should use the same encoding that the XML document itself uses.
This is likely to be UTF-8, but you should check.

Note that in the general case, you should convert arbitrary binary data
into strings using something like base64. In this case it's okay
because the binary data is actually encoded text data.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 24 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2337
by: Pete Davis | last post by:
I've never done this in C# so I don't know what the appropriate way of doing it is. I've got an array of bytes and I need to convert the array into "usable" data. For example, the first 4 bytes need to be converted to an enum. The next 4 bytes to a 32-bit int. And so on. I'm basically populating a struct with the data. How does one do this in C#? Thanks.
4
9219
by: Kai Bohli | last post by:
Hi all ! This message has been posted on .net.general, but I reposts it here due to lack of replies. This is my first day with Visual Studio and C#, and I'm trying to send "raw data" to the printer port. I found the SendFileToPrinter example below in a knowledge base at MS site It works, but I need to replace the filestream with a memorystream cause there's no need to write files and then load them again just to print. So I rewrote...
8
4559
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in XML, and embedded the array as some child element in an xml file, i.e.: <Mask>bHQAAH4AAABCTX4AAAAAAAAAPgAAACgAAAAQAAAAEAAAAAEAAQAAAAAAQAAAAAAAAAAAAA AA AAAAAAAAAAAAAAAA////AP//AAD//wAA//8AAP//AAD/7wAA//cAALtzAABVeQAAVUAAAFVA...
12
7762
by: Mark Rae | last post by:
Hi, Can anyone please tell me how to convert an unserializeable object say, a System.Web.Mail.MailMessage object, to a byte array and then convert the byte array to a Base64 string? Any assistance gratefully received. Best regards,
13
2845
by: Don | last post by:
When I run the following code, the MemoryStream's Position is always set to 762 instead of 0, which is what I would expect: Dim bmp As Image Dim ms As MemoryStream bmp = New System.Drawing.Bitmap("C:\2068.bmp") ms = New MemoryStream bmp.Save(ms, bmp.RawFormat)
5
26264
by: Naamat | last post by:
Hello, I am the sample FPSEPublish (http://blog.baeke.info/blog/_archives/2005/3/3/393158.html) code to upload a document to Sharepoint (WSS). This works perfectly for samll documents. Problem: When I attempt to upload a huge document (300Megabayte) on a PC with 3.6Gig RAM I am getting a OutOfMemoryException when the program attempts to read the
10
17838
by: Asaf | last post by:
Hi, I am trying to Compress & Decompress a DataSet. When running this code I am receiving the error: System.Xml.XmlException was unhandled Message="Root element is missing." Source="System.Xml" The code:
3
6641
by: grawsha2000 | last post by:
Hi, I'm trying to convert this simple string into image: Dim bytes() as byte()=System.text.Encoding.ascii.GetBytes("123") Dim memStream as System.IO.MemoryStream Dim img as image memStream.Write(bytes,0.bytes.length)
2
10342
by: Laurent Navarro | last post by:
Hello, I am using a library which returns a byte containing RAW data, ie all pixels' color values coded in a byte array without header. I would like to save those data into a JPEG file so I tried to use the MetaFile class. byte data; (...) // Creating the RAW image through the DLL call. MemoryStream memoryStream = new MemoryStream(data);
0
8485
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8930
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8828
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8605
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8677
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6238
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4417
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.