Reputation: 105
When I save the object from TStringList class file content to a file, the file is saved with UTF-8 correctly but UTF-8 with BOM by default.
My code is:
myFile := TStringList.Create;
try
myFile.Text := myData;
myFile.saveToFile('myfile.dat', TEncoding.UTF8)
finally
FreeAndNil(myFile);
end;
In the example the file "myfile.dat" appear as "UTF-8 BOM" encoding.
How can I save the file without BOM?
Upvotes: 7
Views: 9391
Reputation: 19096
You simply have to set the property TStrings.WriteBOM
to false
.
The documentation tells us about this:
Will cause SaveToStream or SaveToFile to write a BOM.
Set WriteBOM to True to cause SaveToStream to write a BOM (byte-order mark) to the stream and to cause SaveToFile to write a BOM to the file.
Upvotes: 14
Reputation: 2350
You can achieve this by creating your own encoding class descended from TUTF8Encoding
and overriding the GetPreamble
method :-
type
TUTF8EncodingNoBOM = class(TUTF8Encoding)
public
function GetPreamble: TBytes; override;
end;
function TUTF8EncodingNoBOM.GetPreamble: TBytes;
begin
SetLength(Result, 0);
end;
Upvotes: 10