StreamWriter erroneous characters

前端 未结 2 1755
借酒劲吻你
借酒劲吻你 2021-01-22 15:45

Having an problem where streamwriter is producing erroneous characters in a csv that I\'m producing. The characters,  , only appear at the start of the file:

2条回答
  •  醉酒成梦
    2021-01-22 16:05

    You have specified that you want to use UTF-8 encoding for the stream and those initial bytes is a valid UTF-8 Byte Order Mark (BOM). The problem is apparently that your viewer/editor doesn't decode the UTF-8 stream correctly. If it only is the BOM that is the problem and you want to create a stream without a BOM you can create your own instance of the UTF8Encoding class:

    var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
    using (StreamWriter sw = new StreamWriter(Response.OutputStream, encoding)) ...
    

    In case you really want to work with ASCII data you should use that encoding instead:

    using (StreamWriter sw = new StreamWriter(Response.OutputStream, Encoding.ASCII)) ...
    

提交回复
热议问题