Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open an ANSI file and Save a a Unicode file using Delphi

For some reason, lately the *.UDL files on many of my client systems are no longer compatible as they were once saved as ANSI files, which is no longer compatible with the expected UNICODE file format. The end result is an error dialog which states "the file is not a valid compound file".

What is the easiest way to programatically open these files and save as a unicode file? I know I can do this by opening each one in notepad and then saving as the same file but with the "unicode" selected in the encoding section of the save as dialog, but I need to do this in the program to cut down on support calls.

This problem is very easy to duplicate, just create a *.txt file in a directory, rename it to *.UDL, then edit it using the microsoft editor. Then open it in notepad and save as the file as an ANSI encoded file. Try to open the udl from the udl editor and it will tell you its corrupt. then save it (using notepad) as a Unicode encoded file and it will open again properly.

like image 471
skamradt Avatar asked Oct 01 '08 16:10

skamradt


2 Answers

This is very simple to do with my TGpTextFile unit. I'll put together a short sample and post it here.

It should also be very simple with the new Delphi 2009 - are you maybe using it?

EDIT: This his how you can do it using my stuff in pre-2009 Delphis.

var
  strAnsi   : TGpTextFile;
  strUnicode: TGpTextFile;
begin
  strAnsi := TGpTextFile.Create('c:\0\test.udl');
  try
    strAnsi.Reset; // you can also specify non-default 8-bit codepage here
    strUnicode := TGpTextFile.Create('c:\0\test-out.udl');
    try
      strUnicode.Rewrite([cfUnicode]);
      while not strAnsi.Eof do
        strUnicode.Writeln(strAnsi.Readln);
    finally FreeAndNil(strUnicode); end;
  finally FreeAndNil(strAnsi); end;
end;

License: The code fragment above belongs to public domain. Use it anyway you like.

like image 20
gabr Avatar answered Sep 21 '22 01:09

gabr


Ok, using delphi 2009, I was able to come up with the following code which appears to work, but is it the proper way of doing this conversion?

var
  sl : TStrings;
  FileName : string;
begin
  FileName := fServerDir+'configuration\hdconfig4.udl';
  sl := TStringList.Create;
  try
    sl.LoadFromFile(FileName, TEncoding.Default);
    sl.SaveToFile(FileName, TEncoding.Unicode);
  finally
    sl.Free;
  end;
end;
like image 90
skamradt Avatar answered Sep 22 '22 01:09

skamradt