【问题标题】:Path.Combine not working when combining remote server path with a file path将远程服务器路径与文件路径组合时,Path.Combine 不起作用
【发布时间】:2020-04-21 17:41:23
【问题描述】:

我试图从一个 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 被删除。为什么会这样?

【问题讨论】:

    标签: c# asp.net-mvc visual-studio-2013 path-combine


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 在数据库中,它以单反斜杠存储,我的意思是,\path\to\file.pdf
      • 但是\path\to\file.pdf前面的\ 指的是根。
      【解决方案3】:

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

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

      path\\to\\file.pdf
      

      代替:

      \\path\\to\\file.pdf
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        • 2017-07-12
        • 2010-10-14
        • 1970-01-01
        相关资源
        最近更新 更多