Path.Combine与Server.MapPath组合使用时发生意外行为

本文关键字:意外 Combine Server MapPath 组合 Path | 更新日期: 2023-09-27 18:28:08

以下是简单的两行代码:

public static void RemoveCoverImageForProduct(int productId)
{
    using (var productRepository = new EfProductRepository())
    {
        var product = productRepository.FindById(productId);
        var coverFolderPath = HttpContext.Current.Server.MapPath(@"~/");
        var filePath = Path.Combine(coverFolderPath, product.CoverImagePath);
        if (File.Exists(filePath))
            File.Delete(filePath);
    }
}

Server.MapPath()正在返回:

C:'Users'Sergio'Desktop'MyApp'MyApp.WebUI'

product.CoverImagePath正在返回:

/Public/products/buscar.jpg

在两者上运行Path.Combine的结果,意味着运行后filePath的值为:

/Public/products/buscar.jpg

我期待的是:

C:'Users'Sergio'Desktop'MyApp'MyApp.WebUI'Public'products'buscar.jpg

有什么想法吗?为什么这没有像我预期的那样起作用?

Path.Combine与Server.MapPath组合使用时发生意外行为

Path.Combine的第二个参数的规则是

如果路径2不包括根(例如,如果路径2没有以分隔符或驱动器规范开头),则结果是两个路径的串联,中间有一个分隔符如果路径2包含根,则返回路径2

product.CoverImagePath中的斜线是根,这就是Path.Combine返回的原因

/Public/products/buscar.jpg

假设您知道它以斜杠开头,则可以删除它并将其传递到Path.Combine:

var filePath = Path.Combine(coverFolderPath, product.CoverImagePath.Substring(1));

如果您不确定,请使用条件:

var relativeFilename = Path.IsPathRooted(product.CoverImagePath) 
    ? product.CoverImagePath.Substring(1)
    : product.CoverImagePath;
var filePath = Path.Combine(coverFolderPath, relativeFilename);

都在文档中:

如果路径2不包括根(例如,如果路径2没有启动带有分隔符字符或驱动器规范),结果是两条路径的串联,中间有一个分隔符性格如果路径2包含根,则返回路径2

斜线('/')是一个分隔符,因此您可以返回传入的路径/Public/products/buscar.jpg