Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have XML content in a string that defines its encoding in its declaration. I want to get a byte array from that string and download it to a client browser.

The following works, but I'm not that experienced with encoding and am wondering will I cause something to blow up if I do it this way?

Basically, I'm getting the encoding from the declaration, and using that encoding to convert the XML string to a byte array. Is that how it should work?

var xdoc = XDocument.Parse(xmlString);
var encoding = System.Text.Encoding.GetEncoding(xdoc.Document.Declaration.Encoding);

var encoded = encoding.GetBytes(xmlString);

Response.AppendHeader("Content-Disposition", "attachment; filename=" + xmlData.FileName);
return File(encoded, "text/plain");
share|improve this question

1 Answer 1

up vote 0 down vote accepted

You should put an exception handler around GetEncoding - it'll throw if it doesn't recognise the encoding name. Otherwise you're fine.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.