Hi, you can even go for using SMO to get your task done in a more easy way. Please refer this msdn link.
-Vinay Pugalia
If a post answers your question, please click "Mark As Answer" on that post.
Web : Inkey Solutions
Blog : My Blog
Email : Vinay Pugalia