path.combine()返回意外结果



我正在尝试使用Path.Combine()创建一条路径,但我会得到意外的结果。

using System;
using System.IO;
namespace PathCombine_Delete
{
    class Program
    {
        static void Main(string[] args)
        {
            string destination = "D:\Directory";
            string destination02 = "it";
            string path = "L:\MyFile.pdf";
            string sourcefolder = "L:\";//In other instances, it could be L:\SomeFolderAndMayBeAnotherFolder
            string replacedDetails = path.Replace(sourcefolder + "\", "");
            string result = Path.Combine(destination, destination02, replacedDetails);
            Console.WriteLine(result);
            Console.ReadKey();//Keep it on screen
        }
    }
}

我希望结果D:\DirectoryitMyFile.pdf,但是我得到L:MyFile.pdf

我看不到为什么?我承认这里是傍晚,但是我仍然多次使用path.combine,并且自.NET 4.0以来,它允许通过字符串参数。但是,它似乎忽略了前2个,只读了最后一个。

这是错误

 string replacedDetails = path.Replace(sourcefolder + "\" , "");

您正在添加另一个后斜切,没有发现任何东西可以替换。
删除添加的后斜线给出了正确的字符串以搜索并替换

 string replacedDetails = path.Replace(sourcefolder , "");

但是,您可以避免使用

的所有替换内容和中间变量
 string result = Path.Combine(destination, destination02, Path.GetFileName(path));

我建议使用:

  string replacedDetails = Path.GetFileName(path);

将在不使用字符串替换的情况下处理从路径上删除源文件夹,如果您从其他地方获取path(最终)。

您是否阅读了文档?您是否验证了要传递给Path.Combine()的内容?文档说,我引用:

path1 应该是绝对的路径(例如," d: archives"或" Archives public")。 如果 path2 路径3 也是绝对路径,则组合操作丢弃了所有 以前将路径合并到该绝对路径。

应该暗示问题。

最新更新