Path.Combine not working when combining remote server path with a file path

2.5k Views Asked by At

From an ASP.NET MVC app I am trying to concatenate two paths, a remote server path with a path extracted from database. I am performing below:

string serverPath = @"\\myServer\TempFolder";
string filePath = GetPathFromDatabaseTable();

string finalPath = System.IO.Path.Combine(serverPath, filePath);

GetPathFromDatabaseTable method returns this string:

\\path\\to\\file.pdf

When concatenating using Path.Combine, the result got into finalPath is:

\\path\\to\\file.pdf

So the prefix serverPath \myServer\TempFolder is removed. Why is happening?

3

There are 3 best solutions below

0
On

Dropping the leading slash at the beginning from filePath works as explained here in the solution.

so if in database is stored as \path\to\file.pdf then when I read from database I drop the leading slash at the beggining, so GetPathFromDatabaseTable method returns:

path\\to\\file.pdf

instead of:

\\path\\to\\file.pdf

so then when combining using System.IO.Path.Combine it works perfectly.

0
On

You can use the Uri class to achieve combining a remote and a local path:

string serverPath = @"\\myServer\TempFolder";
string filePath = "\\path\\to\\file.pdf";

Uri serverUri = new Uri(serverPath + filePath);

string finalPath = serverUri.LocalPath;

Which returns

\\myserver\TempFolder\path\to\file.pdf
2
On

Is the query returning \\path\\to\\file.pdf exactly? or is that only a representation in c# debugger.

You should not store \\ as directory separator into the database field. the \\ is only needed to escape the string when you write it in c#. (unless you are using the @"\")

If you use \\ in the database field, the first \\ will be seen as a rooted path and probably removes the previous path.