开发者

A good file path builder library for C#? [closed]

开发者 https://www.devze.com 2022-12-24 06:36 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 8 years ago.

Improve this question

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 开发者_JS百科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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号