c# - Lots of unexpected "nul" caracters at the end of an xml with MemoryStream -


i wrote action user downoad generated xml generated whithout having write on server disk, keep memory.

here code :

public filecontentresult myaction() {   memorystream mystream = new memorystream();   xdocument xml = generatexml(...);   xml.save(mystream );   mystream .position = 0;   return file(mystream.getbuffer(), "text/xml", "myfile.xml"); } 

everything seem work fine, xml correct, can download file, don't understand why have 691920 "nul" caracters @ end of file (the number of caracters seems related length of xml):

enter image description here

where came ? how can rid of them ?

[update] tried :

public filecontentresult myaction() {   xdocument xml = generatexml(...);   byte[] bytes = new byte[xml.tostring().length * sizeof(char)];   buffer.blockcopy(xml.tostring().tochararray(), 0, bytes, 0, bytes.length);   return file(bytes, "text/xml", "myfile.xml"); } 

and didn't "nul" characters. suppose memorystream add caracters @ end of file. in example whith second code problem solved.

but generate word document can't read (xxx.docx cannot opened because there problems contents). suppose have same problem here, memory stream add caracters @ end of file , corrupt it.

the problem you're calling mystream.getbuffer(). getbuffer() method returns underlying array used memorystream, including "spare" parts don't contain real data. documentation:

note buffer contains allocated bytes might unused. example, if string "test" written memorystream object, length of buffer returned getbuffer 256, not 4, 252 bytes unused. obtain data in buffer, use toarray method; however, toarray creates copy of data in memory.

instead of using getbuffer(), use toarray() - or use length of stream know how of buffer use.

note in updated code, you're converting string utf-16 - may mean it's twice size needs be, , may not following encoding claims. wouldn't recommend approach.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -