10

I need to make my delphi app able to check if a file copied using Robocopy is there or not when its path exceeds 255 characters. I have tried the usual "If FileExists(MyFile) then ... " but it always returns "false" even if the file is there.

I also tried to get the file's date but I get 1899/12/30 which can be considered as an empty date.

A File search does not return anything either.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Fab
  • 103
  • 1
  • 4

1 Answers1

10

Prefix the file name with \\?\ to enable extended-length path parsing. For example you would write

if FileExists('\\?\'+FileName) then
  ....

Note that this will only work if you are calling the Unicode versions of the Win32 API functions. So if you use a Unicode Delphi then this will do the job. Otherwise you'll have to roll your own version of FileExists that calls Unicode versions of the API functions.

These issues are discussed in great length over on MSDN: Naming Files, Paths, and Namespaces.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thanks for your reply. This solution works great with local paths such as e:\myfilepath but I remain stuck with UNC paths, even with "If FileExists('\\?\UNC\'+MyFile) then ..." – Fab Jun 01 '13 at 16:24
  • UNC paths work fine here. I'm pretty confident that my answer is all you need. Something else will be wrong. Once you have the `\\?\` prefix you have escaped the 260 limit. – David Heffernan Jun 01 '13 at 16:35
  • 3
    @Fab: If `MyFile` contains a standard UNC path, you have to remove the leading `'\\'` from it when prepending the `'\\?\UNC\'` prefix. IOW, `'\\server\path'` needs to become `'\\?\UNC\server\path'`, not `'\\?\UNC\\\server\path'` like your code is currently doing. – Remy Lebeau Jun 01 '13 at 18:10
  • What Remy says is accurate. Perhaps that's your problem. The article I link to says the same. – David Heffernan Jun 01 '13 at 18:31
  • Remy is right, I forgot that point. I had to use "If copy(MyFile,0,2)='\\' then MyFile:=StringReplace(MyFile, '\\', '\\?\UNC\', [rfReplaceAll, rfIgnoreCase]);" The FileExists works great then. Thanks ! – Fab Jun 02 '13 at 20:02