System.IO.Path
in .NET is notoriously clumsy to work with. In my various projects I keep encountering the same usage scenarios which require repetitive, verbose and thus error-prone code snippets that use Path.Combine
, Path.GetFileName
, Path.GetDirectoryName
, String.Format
, etc. Scenarios like:
- changing the extension for a given file name
- changing the directory path for a given file name
- building a file path using string formatting (like "
Package{0}.zip
") - building a path without resorting to using hard-coded directory delimiters like
\
(since they don't work on Linux on Mono) - etc etc
Before starting to write my own PathBuilder
class or something similar: is there a good (and proven) open-source implementation of such a thing in C#?
UPDATE: OK, just an illustration of what I mean:
string zipFileName = Path.GetFileNameWithoutExtension(directoryName) + ".zip";
zipFileName = Path.Combine(
Path.GetDirectoryName(directoryName),
zipFileName);
A nicer fluent API could look like this:
Path2 directoryName = "something";
Path2 zipFileName = directoryName.Extension("zip");
Or when building a path:
Path2 directoryName = "something";
Path2 directory2 = directoryName.Add("subdirectory")
.Add("Temp").Add("myzip.zip");
instead of
string directory2 = Path.Combine(Path.Combine(Path.Combine(
directoryName, "subdirectory"), "Temp"), "myzip.zip");
I actually did implement something like this in the past, but in a separate project. I've decided now to reuse it as a standalone C# class added "as link" in VisualStudio in my other projects. It's not a cleanest solution, but I guess it will do. If you're interested, you can see the code here.