Change the url of your blogposts from code

Today I migrated my weblog from Sitefinity 3.7 to Sitefinity 4.4. Luckily there is a nice migration manager that comes with Sitefinity 4.x, so it is quite easy to migrate content.

  • February 28, 2012

Today I migrated my weblog from Sitefinity 3.7 to Sitefinity 4.4. Luckily there is a nice migration manager that comes with Sitefinity 4.x, so it is quite easy to migrate content.

After the migrations was done, I noticed that the blogposts were still holding the old url names.

For example, this post will have the following url:

/change-the-url-of-your-blogposts-from-code  

Within the old url structure the url would look like this:

/change-the-url-of-your-blogposts-from-code.aspx  

Notice the page extension on the end.

To change the urls for all blogposts at once, I came up with the following code:

var manager = BlogsManager.GetManager();
var posts = manager.GetBlogPosts ().Where (x => x.Status == ContentLifecycleStatus.Master).ToList ();

foreach (var b in posts) {

    var temp = manager.Lifecycle.CheckOut (b) as BlogPost;
    temp.Urls.Clear ();
    temp.UrlName = Regex.Replace (b.Title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");

    var post = manager.Lifecycle.CheckIn (temp) as BlogPost;
    manager.RecompileAndValidateUrls (post);
    manager.Lifecycle.Publish (post);
    manager.SaveChanges ();

}
manager.SaveChanges();

We loop through all of the blogposts and clear the existing urls. Then we generate a new UrlName based on the title of the blogpost (with use of RegEx).

We call the RecompileAndValidateUrls method to regenerate the new urls for the post and finally we publish and save the post.

This way I recreated all urls for all posts in just a few seconds.


Image Description

Daniel Plomp

Entrepreneur, Senior Software Engineer .NET, Sitefinity Solution specialist, Orchard CMS enthusiast, Product Owner

All Author Posts

Got another minute? Check out:

Image Description

Call us

+31 (0) 36-2000196
Image Description

Address

Grote Beer 57, 3893 DJ Zeewolde
NLThe Netherlands

Please sign in

Signin to manage your account.

Do not have an account? Signup

OR