Cita:
Empezado por Casimiro Notevi
Vaya, eso es de 2015.
Se me ocurre que también puedes hacer una sustitución de las ñ,á,é,í,ó,ú antes de importar las líneas.
|
Gracias Casimiro!! es la solución que al final he implementado. No es la mas optima, puesto que si el fichero en algún momento incluye otros caracteres en UTF8 tendré entonces que modificar nuevamente el código. Pero de momento me sirve como solución.
Aquí dejo el código que he implementado:
Código Delphi
[-]
function UTF8ToAnsii(const value: string): string;
const
SpecialChars: array[0..5] of string = ('ñ', 'á', 'é', 'í', 'ó', 'ú');
var
i: LongInt;
begin
result := value;
for i := 0 to High(SpecialChars) do
result := StringReplace(result,
SpecialChars[i],
TEncoding.ANSI.GetString(TEncoding.UTF8.GetBytes(SpecialChars[i])), [rfReplaceAll]);
end;
function RepairFileUTF8(const AFileName: string): boolean;
var
content: string;
begin
try
result := false;
content := Tfile.ReadAllText(AFileName);
content := UTF8Decode(UTF8ToAnsii(content));
Tfile.WriteAllText(AFileName, content, TEncoding.UTF8);
result := true;
except
on E: Exception do
MessageDlg(E.message, mtError, [mbOK], 0);
end;
end;
function IsValidUTF8Format(const AFileName: string): Boolean;
var
intento: integer;
begin
result := false;
intento := 2;
repeat
try
dec(intento);
Tfile.ReadAllText(AFileName, TEncoding.UTF8);
result := true;
except
on E: Exception do begin
if (e.Message = SNoMappingForUnicodeCharacter) then begin
if (intento > 0) then
RepairFileUTF8(AFileName)
else
MessageDlg('Revise caracteres especiales UTF8 en el fichero', mtError, [mbOK], 0);
end;
end;
end;
until result or (intento <= 0);
end;
y la forma de utilizarlo es:
Código Delphi
[-]
if not IsValidUTF8Format(NameFile) then
MessageDlg('El fichero no tiene un formato valido ', mtError, [mbOK], 0)
else
OpenFile(NameFile);
Gracias por vuestro tiempo y las soluciones aportadas.
Un saludo