Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Tpath.Combine('c:', 'myfile.txt') leaves out DirSeperator

So when I run

TPath.Combine('c:', 'myfile.txt');

in Delphi XE2 then I get 'C:myfile.txt' in return. This is not what I expect and it is not a valid path in windows. I would expect TPath.Combine to be a call to the windows API ( http://msdn.microsoft.com/en-us/library/fyy7a5kt%28v=vs.110%29.aspx ) or to have the same behaviour as the API.

Is there something I'm doing wrong? Can I "fix" the behaviour of TPath.Combine? Or do I have to search all uses in my code and replace it with a string concatenation with a '\' in between?

like image 817
user3331950 Avatar asked Dec 25 '22 04:12

user3331950


2 Answers

I think that the behaviour is correct, and as designed. There is a difference between C:myfile.txt and C:\myfile.txt. The Windows documentation calls this out quite explicitly:

If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent "change directory" operation on that disk. Examples of this format are as follows:

  • "C:tmp.txt" refers to a file named "tmp.txt" in the current directory on drive C.
  • "C:tempdir\tmp.txt" refers to a file in a subdirectory to the current directory on drive C.

If the RTL function TPath.Combine added a separator after a drive designator, then there would be no way for you to use TPath.Combine to produce a path like "C:tmp.txt". So, if you want a directory separator, you'll need to supply one yourself:

TPath.Combine('c:\', 'myfile.txt');

Note that the .net framework method Path.Combine on which the Delphi RTL class TPath is loosely modelled behaves the same was the the Delphi RTL equivalent.

Related:

  • Why Path.Combine doesn't add the Path.DirectorySeparatorChar after the drive designator?
  • Path.Combine() does not add directory separator after drive letter
like image 177
David Heffernan Avatar answered Dec 27 '22 20:12

David Heffernan


When combining folder names and folder files it is always good (if you don't want the default behaviour when a drive designator is given as a path) to put folder name through IncludeTrailingPathDelimiter method. This method will add trailing delimiter to your path if there isn't one

TPath.Combine(IncludeTrailingPathDelimiter('c:'), 'myfile.txt');
like image 22
SilverWarior Avatar answered Dec 27 '22 20:12

SilverWarior