1

从 ASP.NET MVC 应用程序中,我尝试连接两个路径,一个远程服务器路径和一个从数据库中提取的路径。我在下面表演:

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

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

GetPathFromDatabaseTable 方法返回此字符串:

\\path\\to\\file.pdf

使用 Path.Combine 连接时,进入 finalPath 的结果是:

\\path\\to\\file.pdf

因此前缀 serverPath \myServer\TempFolder 被删除。为什么会发生?

4

3 回答 3

1

您可以使用Uri该类来实现远程和本地路径的组合:

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

Uri serverUri = new Uri(serverPath + filePath);

string finalPath = serverUri.LocalPath;

哪个返回

\\myserver\TempFolder\path\to\file.pdf
于 2020-04-21T17:48:51.150 回答
0

查询是否\\path\\to\\file.pdf准确返回?或者这只是 c# 调试器中的一种表示形式。

您不应该目录\\分隔符存储到数据库字段中。仅当您在\\c# 中编写字符串时才需要转义字符串。 (除非您使用的是@"\"

如果您\\在数据库字段中使用,第一个\\将被视为根路径,并且可能会删除以前的路径。

于 2020-04-21T17:49:08.823 回答
0

从 filePath 的开头删除前导斜杠按照解决方案中的说明工作

因此,如果在数据库中存储为 \path\to\file.pdf 那么当我从数据库中读取时,我会在开头删除前导斜杠,因此 GetPathFromDatabaseTable 方法返回:

path\\to\\file.pdf

代替:

\\path\\to\\file.pdf

因此,当使用 System.IO.Path.Combine 进行组合时,它可以完美运行。

于 2020-04-21T21:21:13.493 回答