percentum
percentum

Reputation: 153

What's the correct way to build up a file path from multiple strings?

Here's how I'm currently building a file path from multiple strings (actual names and values from my code have been replaced for the purpose of this question).

const string STATIC_PART_OF_PATH = "/";

var topLevel = string.Join("/","A","B","C","D");          // "A/B/C/D"

string node1 = string.Format("{0}/Node1", topLevel);      // "A/B/C/D/Node1"
string node2 = topLevel + STATIC_PART_OF_PATH + "Node2";  // "A/B/C/D/Node2"
string node3 = topLevel + STATIC_PART_OF_PATH + "Node3";  // "A/B/C/D/Node3"

I am unsure if this is the best convention/practice.

What's the correct way to build up a full string path?

Upvotes: 0

Views: 641

Answers (1)

Eldar Dordzhiev
Eldar Dordzhiev

Reputation: 5135

I think the best way of building filesystem path is to use Path.Combine, even for string literals.

var path = Path.Combine("ABCD", "Node1", "Node2", "Node3");

Anyway, paths containing both "\" and "/" should work correctly, but canonical way is of course Path.Combine.

Upvotes: 4

Related Questions