I wrote an action for the user to download the created xml file without having to write it to the server disk, but save it in memory.
Here is my 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 looks fine, the XML is correct, I can upload the file, but I donβt understand why I have 691920 "zero" characters at the end of my file (the number of these characters seems to be related to the length of the xml):

Where did they come from? How can I get rid of them?
[Update] I tried this:
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 I did not get the characters "nul". Therefore, I believe that MemoryStream adds extra characters at the end of the file. So in my example with the second code, my problem is solved.
But I also create a Word document that I cannot read (xxx.docx cannot be opened because there are problems with the content). I suppose I have the same problem, the memory stream adds extra characters to the end of the file and corrupts it.
source share