简体   繁体   中英

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

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?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM