There is a StringBuilder from which we get the text we want to write. But here's the problem, I tried two ways to write to the file.

Initial data:
sb is the same StringBuilder
fullFileName is the full path to the * .csv file format

The first way:

 var file = Encoding.UTF8.GetBytes(sb.ToString()); File.WriteAllBytes(fullFileName, file); 

The second way:

 System.IO.File.WriteAllText(fullFileName, sb.ToString(), Encoding.UTF8); 

I looked in Notepad ++ , the first method writes the file in the “UTF8 (Without BOM)” encoding, and the second one in “UTF8” . The second file has no problems with the encoding and everything is readable, and the first one gives out krakozyabra, all this when opening in Excell. File format * .csv . Please explain what is the cause of the problem and how can it be solved in the first method?

    1 answer 1

    Apparently, in the absence of BOM, Excel does not know how to auto-detect the encoding, and considers it to be UTF-16 encoding. As a solution on the side of the user, this can be approached: creating a clean table, and importing it through “Data” → “From text”: Excel recognizes CSV, and offers to choose an encoding.

    If you want to write a BOM to text: Encoding.GetBytes does not know that you are not coding text, but all the text, and does not add a BOM. You can get the BOM yourself using Encoding.UTF8.GetPreamble() , write these bytes to a file, and then append the rest.

    Unfortunately, I did not find the File.AppendAllBytes method, so you will have to either byte the bytes in memory

     var file = Encoding.UTF8.GetBytes("some data"); var fileWithBom = Encoding.UTF8.GetPreamble().Concat(file).ToArray(); File.WriteAllBytes(fullFileName, file); 

    (which is probably not the most effective method), or write in two steps:

     using (var stream = File.Create(fullFileName)) { var bom = Encoding.UTF8.GetPreamble(); stream.Write(bom, 0, bom.Length); var file = Encoding.UTF8.GetBytes("some data"); stream.Write(file, 0, file.Length); } 
    • At first I tried it through Union - I gave it to the Concat , but with the Concat it worked. Thank you) - Denis Bubnov
    • @DenisBubnov: It seems to me that Union returns a union as for sets. And Concat should work, yes. - VladD February