fredag den 13. december 2013

Server.MapPath inside Sitecore tasks

From time to time, when developing tasks for Sitecore, you need to map a virtual path to a physical file in the file system.

The way to do this, is to call the function MapPath on the Server object located on the current HttpContext object.

This will not work in tasks, since there is no HttpContext (since we are running on a separate thread) - so we have to come up with some other way to map this, in case the HttpContext is missing.

This is the solution we have come up with:

public static string MapFilePath(string filePath)
{
    if (string.IsNullOrEmpty(filePath))
    {
        throw new ArgumentException("filePath must not be empty", "filePath");
    }

    if (HttpContext.Current != null)
    {
        return HttpContext.Current.Server.MapPath(filePath);
    }

    return HttpRuntime.AppDomainAppPath + filePath.Replace('/', '\\');
}

If there is a HttpContext, we just do like we normally do, since that is prettier - but if there is no HttpContext, we have to do some string manipulation to get the desired result.

Since the URL has to use back slashes instead of forward slashes, we have to replace those.

This results in usable URL's being returned, no matter if you are in a task or not :-)

Ingen kommentarer:

Send en kommentar