I wrote an action for a user to downoad a generated xml generated whithout having to write it on the server disk, but keep it into 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 seem to work fine, the XML is correct, I can download the file, but I don't understand why I have 691920 "nul" caracters at the end of my file (the number of those caracters seems to be related to the length of the xml):
Where do they came from ? How can I 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 didn't get the "nul" characters. So I suppose it is the MemoryStream which add extra caracters at the end of the file. So in my example whith the second code my problem is solved.
But I also generate a Word document which I can't read (xxx.docx cannot be opened because there are problems with the contents). I suppose I have the same problem here, the memory stream add extra caracters at the end of the file and corrupt it.