How to GetBytes() in C# with UTF8 encoding with BOM?

前端 未结 4 1000
余生分开走
余生分开走 2020-11-27 16:06

I\'m having a problem with UTF8 encoding in my asp.net mvc 2 application in C#. I\'m trying let user download a simple text file from a string. I am trying to get bytes arra

4条回答
  •  清酒与你
    2020-11-27 16:47

    Try like this:

    public ActionResult Download()
    {
        var data = Encoding.UTF8.GetBytes("some data");
        var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
        return File(result, "application/csv", "foo.csv");
    }
    

    The reason is that the UTF8Encoding constructor that takes a boolean parameter doesn't do what you would expect:

    byte[] bytes = new UTF8Encoding(true).GetBytes("a");
    

    The resulting array would contain a single byte with the value of 97. There's no BOM because UTF8 doesn't require a BOM.

提交回复
热议问题