检测两条路径是否相同

时间:2015-06-28 07:32:15

标签: c#

我有两条路:

\\10.11.11.130\FileServer\Folder2\Folder3\
\\10.11.11.130\d$\Main\FileServer\Folder2\Folder3\

我想检测两条路径是否相同。

我想要它,因为我试图将一个文件移动到另一个目录。 因此,对于上面的路径,会抛出异常。

我知道我可以使用try和catch,但还有另一种方法吗?

我考虑过从第二条路径中移除d$\Main然后进行比较,但并不总是如此。

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

您可以使用这样的方法检查是否相等:

public static bool PathsSame(string pth1, string pth2)
{

    string fName = System.IO.Path.GetRandomFileName();
    string fPath = System.IO.Path.Combine(pth1, fName);
    System.IO.File.Create(fPath);
    string nPath = System.IO.Path.Combine(pth2, fName);
    bool same = File.Exists(nPath);
    System.IO.File.Delete(fPath);
    return same;
}

这模拟了检查路径是否相同的行为,您可以创建具有唯一名称的文件并检查其是否存在于其他目录中。然后你可以删除创建的文件,因为它不再需要了。这不是最好的解决方案,但这可能就足够了。

这也不能处理可能发生的错误。对于错误处理,请查看:https://msdn.microsoft.com/en-us/library/vstudio/as2f1fez(v=vs.110).aspx

相关问题