Friday, February 09, 2007

Get media path by file path


This code snippet applies to 5.1.1/5.2.

Here is the code snippet that does the job:

string fullPath = @"D:\wwwroot\Clean5.2.0.12\upload\images\Devil-Skype!.png";

// mapping the path

string mappedPath = Sitecore.Resources.Media.MediaPath.MapPath(fullPath);

// switching the context to shell

Sitecore.Context.SetActiveSite("shell");

// setting the actual media path

string mediaPath = Sitecore.Resources.Media.MediaPath.CreatePath(mappedPath).Paths.FullPath;

// next you may switch back to website

The site switch is necessary since the CreatePath method deals with the content database of the context site which is null for the website by default.

If you don’t want to change the site context, you should add the content database definition to the website:

<site

name="website"

...

content="master" or “web”

...

This way your code will look like:

string fullPath = @"D:\wwwroot\Clean5.2.0.12\upload\images\Devil-Skype!.png";

string mappedPath = Sitecore.Resources.Media.MediaPath.MapPath(fullPath);

string mediaPath = Sitecore.Resources.Media.MediaPath.CreatePath(mappedPath).Paths.FullPath;

0 comments: