Search code examples
delphidelphi-7

Delphi 7, TFileStream cant open files with special characters


This line:

TFileStream.Create(fileName, fmOpenRead or fmShareDenyNone);

drops an exception if the filename contain something like ñ


Solution

  • You are, ultimately calling CreateFileA, the ANSI API, and the characters you use have no ANSI encoding. The only way to get beyond this is to open the file with CreateFileW, the Unicode API.

    You might not realise that you call CreateFileA, but that's how the Delphi 7 file stream is implemented.

    One easy way to solve your problems is to upgrade to the latest Delphi which has good support for the native Windows Unicode API.

    If you are stuck with ANSI Delphi then you still need to call CreateFileW. You can do this to create a file handle. You'll need to pass a UTF-16 string to that API. Use WideString to store it. You'll also need to get the filename from the user in UTF-16 form. Which means a call to GetOpenFileNameW or IFileDialog. Create a stream by passing the file handle to THandleStream.

    To make all this possible you would use the TNT Unicode libraries. They work well but will impose a big port on you.

    Frankly, the right way forward is to use modern tools that support Unicode.