【问题标题】:C# Combining two relative network pathsC# 组合两个相对网络路径
【发布时间】:2020-09-03 11:37:36
【问题描述】:

System.IO.Path 方法在组合两条路径时给了我一些非常奇怪的结果;

string Dir = "\\server1\\customers\\Test";
string path = "..\\..\\customers\\Test\\hello.pbt";

path = Path.Combine(Dir, path);
// path = "\\server1\\customers\\Test\\..\\..\\customers\\Test\\hello.pbt"

现在我想组合这些路径:

path = "\\server1\\customers\\Test\\hello.pbt" // aim

但是使用 Path.GetFullPath 方法,它不会按原样返回到服务器

path = Path.GetFullPath(path)
// path = "\\server1\\customers\\customers\\Test\\hello.pbt"

我已经尝试了Combining two relative paths with C#答案中描述的所有方法

【问题讨论】:

  • Combine 方法只是将第一个与第二个连接起来。实际上,结果并不奇怪,而是在意料之中。什么是“组合”的规则会导致预期的结果?
  • 是的,我知道,但它应该倒退两次而不是一次!

标签: c# path


【解决方案1】:

问题似乎是 .NET(可能还有 Windows)没有将 \\server1\customers 的父级视为 \\server

从技术上讲,\\server 似乎不是 valid UNC path(即您不能直接将文件存储在那里)。

var thisWorks = Directory.GetParent(Dir);

var thisIsNull = Directory.GetParent(Directory.GetParent(Dir).FullName);

因此,当您请求 ..\\..\\ 时,它实际上会忽略其中一个,因为它推断它不能在目录树的更高位置...

【讨论】:

  • 非常感谢您的回答!!你完全正确,server1 不是有效的 UNC 路径。我不能在那个“文件夹”中创建任何东西。它帮助我理解了问题
  • @tony_370 不客气。我也不知道它,直到我自己玩了它并阅读了它。
  • DirectoryInfo 告诉我服务器路径不存在。是否有任何功能可以解决我的"..\",但不检查文件夹是否存在?
  • 简短的回答是你需要自己写@tony_370。
猜你喜欢
  • 2019-03-12
  • 2020-05-26
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 2011-04-04
  • 2012-02-09
  • 2016-05-16
相关资源
最近更新 更多