0

I recently learned about Path.Combine which combines two strings into a path, but I wonder what is, if any advantage of using Path.Combine compared to what we currently use in production which is something like the following:

var path = @":\somepath\"; var filename = postedFile.FileName;

var fullPath = path + filename;

Is it better going forwards to use Path.Combine(path, fileName)

Thanks

Arcane92
  • 57
  • 1
  • 10
  • 1
    Using `Path.Combine()` will help prevent you from missing a \ or having two \\ by mistake. – Matthew Watson Nov 22 '17 at 10:43
  • Did you even care to read the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=netframework-4.7.1#System_IO_Path_Combine_System_String_System_String_)? It's pretty clear the advantages – Camilo Terevinto Nov 22 '17 at 10:44

3 Answers3

2

may be the question is a little bit academic but valid in my opinion, I think the designers/architects of .NET System.IO namespace wanted to provide the functionality of combining paths because it belongs to the logic of the IO namespace, also the combine hides the use of the '\' path control character, if .NET runs on another system where e.g. '|' is the path separator then your code will not work

Siraf
  • 1,133
  • 9
  • 24
0

Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

Reference link: What is the advantage of using Path.Combine over concatenating strings with '+'?

0

To Answer your question is the shortest way possible: Yes.

The MSDN article is a good start to understand what Path.Combine actually does and doesn't do.

The mostly interesting part of Combine is that it will try to add separators when needed:

string disk = "c:";
string file= "text.txt";
string result= Path.Combine(disk,file); 
//result will be c:\text.txt
Harmelyo
  • 141
  • 6