How to handle very long file names (with TPath)?

2019-06-28 05:37发布

问题:

I have a program that downloads some files from Internet. The file name could be very long (100 chars). The user may choose to save these these files in a folder that has a very long name (200 chars). So, the total length of the path is over 260 chars.

I tried to create a function that checks if the path is too long and truncates the filename so the whole path will be exactly 260 chars. But functions in TPath class fails to work if the path is over 260 chars. More exactly GetDirectoryName raises a specific error when the path is over 260 chars, so I cannot use it to split the folder from file name.

A major design flaw in Delphi?
I think that TPath raising an error when working on long file names is a big flaw. Simply using GetDirectoryName to READ (not to write) will simply crash your program. TPath should allow processing long paths. MAYBE it should raise the error ONLY when you try to WRITE files with long path. But not even then. NTFS accepts long paths. So, why Delphi should force you to stick to 260? Some programs can handle longs paths. For example, I use Total Commander (never Explorer) so I am not affected by the long file name issue.

Any idea on how to treat this case?
Note: The download process is automated so I won't stop to ask the user to enter a new file name for each file that fails to be under 260 chars. I want to handle this silently.

回答1:

Personally, my opinion is that TPath is simply wrong here. To assert that Windows paths cannot be greater than 260 characters is simply denying reality. What's more, to deny you the ability to perform text processing on paths is really quite inexplicable. In my opinion then, TPath should be avoided.

Which leads you back to the good old days. You can call ExtractFileDir from SysUtils. It works as well as it ever did.