A good file path builder library for C#?

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.

Answers


You might also want to checkout the "NDepend.Helpers.FileDirectoryPath" library.


You should take a look at the enhancements to Path in v4 of the framework first.

For example, Path.Combine will now accept multiple path fragments, rather than having to nest them.


System.IO.Path already covers the following from your list:

  • changing the extension for a given file name
  • changing the directory path for a given file name
  • building a path without resorting to using hard-coded directory delimiters like \ (since they don't work on Linux on Mono)

And you can easily create a class or some extensions methods to do the remaining, based on the Path class.


FluentPath looks nice and neat.


Need Your Help

How to iterate through a module's functions

python functional-programming getattr

I have this function call after importing foo.py. Foo has several methods that I need to call e.g. foo.paint, foo.draw:

Place cookies banner very top of the page and always at the center

javascript html css cookies resolution

The policy of my country forces me to put a warning banner cookies for my site. I put it by the following code: