Thursday, March 13, 2008

Silverlight 2.0 Convert Relative Url Paths to Absolute

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/silverlight_20_convert_relative_url_paths_to_absolute.htm]

As you've probably heard, Silverlight 2.0 Beta 1 is out. You can get it from Silverlight.Net. And Bill Reiss is starting another great tutorial series on Silverlight games.

 

I see a lot of breaking changes (as documented on MSDN), and I'll blog more about my adventures upgrading. One change is that it seems like you need Absolute urls in a few more places (like for accessing xml files or images). Because I like to think in terms of relative urls, here's an easy utility to convert relative to absolute. It should handle both file paths (file:///aaa) and web (http://aaa).

 

    public static string GetAbsoluteUrl(string strRelativePath)
    {
      if (string.IsNullOrEmpty(strRelativePath))
        return strRelativePath;

      string strFullUrl;
      if (strRelativePath.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
        || strRelativePath.StartsWith("https:", StringComparison.OrdinalIgnoreCase)
        || strRelativePath.StartsWith("file:", StringComparison.OrdinalIgnoreCase)
        )
      {
        //already absolute
        strFullUrl = strRelativePath;
      }
      else
      {
        //relative, need to convert to absolute
        strFullUrl = System.Windows.Application.Current.Host.Source.AbsoluteUri;
        if (strFullUrl.IndexOf("ClientBin") > 0)
          strFullUrl = strFullUrl.Substring(0, strFullUrl.IndexOf("ClientBin")) + strRelativePath;
      }

      return strFullUrl;
    }

 

More to come soon...

 

No comments:

Post a Comment