May 5, 2022

IWebHostEnvironment MapPath Extension

Brings MapPath() to .NET Core

public static class IWebHostEnvironmentExtender
{
    /// <summary>
    /// Maps a virtual path that begins with '~' to its corresponding physical path within the web root (wwwroot) directory.
    /// </summary>
    /// <remarks>Use this method to resolve virtual paths in web applications when accessing files or
    /// directories under the web root. If the input path does not start with '~', it is returned unchanged.</remarks>
    /// <param name="whe">The <see cref="IWebHostEnvironment"/> instance that provides information about the web hosting environment,
    /// including the web root path.</param>
    /// <param name="path">The virtual path to map. If the path starts with '~', it will be replaced with the web root path.</param>
    /// <returns>The physical path corresponding to the provided virtual path if it starts with '~'; otherwise, returns the
    /// original path.</returns>
    public static string MapWwwRootPath(this IWebHostEnvironment whe, string path)
    {
        return MapToRootPath(whe.WebRootPath.AsSpan(), path.AsSpan());

    }

    /// <summary>
    /// Maps a virtual path that begins with '~' to the physical content root path of the specified web host
    /// environment.
    /// </summary>
    /// <remarks>Use this method to resolve application-relative paths in scenarios where the content root
    /// path may vary, such as in different hosting environments.</remarks>
    /// <param name="whe">The web host environment that provides the content root path used for mapping.</param>
    /// <param name="path">The virtual path to map. If the path starts with '~', it is resolved relative to the content root path.</param>
    /// <returns>The physical path corresponding to the provided virtual path, or the original path if it does not start with
    /// '~'.</returns>
    public static string MapContentRootPath(this IWebHostEnvironment whe, string path)
    {
        return MapToRootPath(whe.ContentRootPath.AsSpan(), path.AsSpan());
    }

    internal static string MapToRootPath(
        ReadOnlySpan<char> rootPath, 
        ReadOnlySpan<char> path)
    {
        var pathSafe = path.Trim();
        if (pathSafe.IsEmpty)
            return path.ToString();

        var ix = pathSafe.IndexOf('~');
        var restOfPathSafe = pathSafe[1..];
        var res = (ix == 0) ? string.Concat(rootPath, restOfPathSafe) : path.ToString();

        return res;
    }

}

No comments: