gilly3
gilly3

Reputation: 91497

Getting URL from file path in IHttpHandler (Generic handler)

In my IHttpHandler class (for an .ashx page), I want to search a directory for certain files, and return relative urls. I can get the files, no problem:

string dirPath = context.Server.MapPath("~/mydirectory");
string[] files = Directory.GetFiles(dirPath, "*foo*.txt");
IEnumerable<string> relativeUrls = files.Select(f => WHAT GOES HERE? );

What is the easiest way to convert file paths to relative urls? If I were in an aspx page, I could say this.ResolveUrl(). I know I could do some string parsing and string replacement to get the relative url, but is there some built-in method that will take care of all of that for me?

Edit: To clarify, without doing my own string parsing, how do I go from this:

"E:\Webs\WebApp1\WebRoot\mydirectory\foo.txt"

to this:

"/mydirectory/foo.txt"

I'm looking for an existing method like:

public string GetRelativeUrl(string filePath) { }

Upvotes: 3

Views: 4989

Answers (2)

atlaste
atlaste

Reputation: 31116

I can imagine a lot of people having this question... My solution is:

public static string ResolveRelative(string url)
{
    var requestUrl = context.Request.Url;
    string baseUrl = string.Format("{0}://{1}{2}{3}", 
        requestUrl.Scheme, requestUrl.Host, 
        (requestUrl.IsDefaultPort ? "" : ":" + requestUrl.Port), 
        context.Request.ApplicationPath);

    if (toresolve.StartsWith("~"))
    {
        return baseUrl + toresolve.Substring(1);
    }
    else
    {
        return new Uri(new Uri(baseUrl), toresolve).ToString();
    }
}

update

Or from filename to virtual path (haven't tested it; you might need some code similar to ResoveRelative above as well... let me know if it works):

public static string GetUrl(string filename)
{
    if (filename.StartsWith(context.Request.PhysicalApplicationPath))
    {
        return context.Request.ApplicationPath +     
            filename.Substring(context.Request.PhysicalApplicationPath.Length);
    }
    else 
    {
        throw new ArgumentException("Incorrect physical path");
    }
}

Upvotes: 1

otakustay
otakustay

Reputation: 12395

try System.Web.Hosting.HostingEnvironment.MapPath method, its static and can be accessed everywhere in web application.

Upvotes: 0

Related Questions