tags:

views:

249

answers:

2

I'm using this to write to the Response stream:

    using (var writer = new StringWriter())
    {
        context.Server.Execute(virtualpath, writer);
        string s = writer.ToString().Replace(...);
        context.Response.Write(s);
    }

But I'm getting a byte order mark in the response. Am I screwing up the encoding? How do I NOT return the BOM?

EDIT: SOrry Rubens, my first example was incorrect.

+1  A: 

Try this:

context.Server.Execute(virtualpath, context.Response.Output);

EDIT: So, try this to force your encoding:

MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
context.Server.Execute(virtualpath, writer);
context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()).Replace(...));
Rubens Farias
+1  A: 

Server.Execute() returns an encoded stream, but StringWriter() is intended to store simple .NET strings (which are 16-bit Unicode and don't have a BOM) and doesn't know how to decode the incoming bytes. So, the BOM in the response becomes literal characters in your string.

Try writing to a MemoryStream() instead, then decode that back into a string using whichever encoding (UTF-8 or whatever) that the Server.Execute() is passing back. Then you can parse it and write it back to your Response.

richardtallent