38

I'm working on a C# project where I must build paths to various files and folders. These are all under one root folder which I have specified in my Web.config file.

For example:

  1. "start with: "D:\builds\" from my Web.config
  2. Pass to GetRelativePath() to get "D:\builds\5.2\5.2.9751"
  3. Then pass to GetAutoSuitePath() to get "D:\builds\5.2\5.2.9751\AutoSuite\"
  4. Then pass to ParseBrLog which will read "D:\builds\5.2\5.2.9751\AutoSuite\AASanity.csv"

My paths are correct, but I just want to know what the best practice is for incomplete paths. Should I add a "\" to the end of every folder ("D:\Builds\5.2\" + "test.txt"), or add one to the start of every folder/file I add to the path ("D:\Builds" + "\5.2" + "\test.txt")? Currently, I'm, doing it both ways, and want to choose one uniform way of doing it.

zalpha314
  • 1,444
  • 4
  • 19
  • 34
  • 2
    Possible duplicate of *[How do I join two paths in C#?](http://stackoverflow.com/questions/961704/how-do-i-join-two-paths-in-c)*. – Peter Mortensen Mar 21 '14 at 09:14

2 Answers2

97

Use the Path class to build up your paths. It will do the right thing.

Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.

var full = Path.Combine(baseDir, dirFragment);
Oded
  • 489,969
  • 99
  • 883
  • 1,009
9

Use Path.Combine to concatenate path tokens.

If the path is a file to set/change the extension use Path.ChangeExtension.

Matteo Migliore
  • 925
  • 8
  • 22