In a break to discussing bitflags, I thought I'd mention a wee issue that I find to be an occasional annoyance: File paths, and how to go about constructing them while making sure all the fiddly path delimiters are dealt with correctly.
Say I have a directory tree that is rooted somewhere, say C:\Foo. I have nested folders within that, say C:\Foo\Bar and C:\Foo\Bar\Too
Occasionally I need to call a method and pass it a path such as C:\Foo\Bar\Too, but I don't actually have that path on hand. All I know is that I get the path by adding 'C:\Foo', 'Bar', and 'Too' together in a meaningful way that results in a path the OS will understand.
So, I could write code like this:
CallMethod(IncludeTrailingPathDelimiter('C:\Foo') +
IncludeTrailingPathDelimiter('Bar') + 'Too');
I may even need to include an additional trailing path delimiter depending on the call semantics, which further complicates matters, like this:
CallMethod(IncludeTrailingPathDelimiter('C:\Foo') + IncludeTrailingPathDelimiter('Bar') + IncludeTrailingPathDelimiter('Too'));
or even like this:
CallMethod(IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter('C:\Foo') +
IncludeTrailingPathDelimiter('Bar') + 'Too'));
See. Icky isn't it?
What I really want is a tool to take a bunch of bits of a file path and assemble it all for me and give it back all ready to go. So, here's a little utility function that does just that (excuse the formatting - I'm still figuring out how to put nice code formatting in a blog without using screen grabs!):
Function ConstructFilePath
(const Paths : Array of TFileName;
const WantTrailingDelimiter : Boolean) : TFileName;
var I : Integer;
begin
Result := Paths[Low(Paths)];
for I := Succ(Low(Paths)) to High(Paths) do
Result := IncludeTrailingPathDelimiter(Result) + Paths[I];
if WantTrailingDelimiter then
Result := IncludeTrailingPathDelimiter(Result)
else
Result := ExcludeTrailingPathDelimiter(Result);
end;
So, to construct my FooBarToo path with a trailing delimiter and pass it to the method, I can now do this:
CallMethod(ConstructFilePath(['C:\Foo', 'Bar', 'Too'], True));
Which just seems so much nicer and easier to understand. :-)
Raymond.
Friday, September 26, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment