Today I found some old source code. Someone wanted to write a file in the old OEM codepage. Therefore he wrote a small function that encapsulates the Windows API CharToOem function.
class function TStrUtil.ANSIToOEM(const ANSI: string): string;
var
sBuffer: AnsiString;
begin
if ANSI = '' then
Exit('');
SetLength(sBuffer, Length(ANSI));
if CharToOem(PChar(ANSI), PAnsiChar(sBuffer)) then
Result := string(sBuffer)
else
Result := ANSI;
end;
After that he added the OEM string to a TStringList and saved the TStringList to a file.
function TMyForm.SaveTheFile(const AFileName: string)
var
pList: TStringList;
begin
pList := TStringList.Create;
try
pList.Add(TStrUtils.ANSIToOEM('ÄÖÜ'));
pList.SaveToFile(AFileName);
finally
pList.Free;
end;
end;
I’m surprised that this code does work. Since Delphi 2010 strings are Unicode strings. This means that the OEM string is stored in a Unicode string variable.
Instead, I think is is much easier to use the wonderful TEncoding class.
function TMyForm.SaveTheFile(const AFileName: string)
var
pList: TStringList;
pOEMEncoding: TEncoding;
begin
pOEMEncoding := nil;
pList := TStringList.Create;
try
pOEMEncoding := TEncoding.GetEncoding(437);
pList.Add('ÄÖÜ');
pList.SaveToFile(AFileName, pOEMEncoding);
finally
pList.Free;
pOEMEncoding.Free:
end;



