I have programatically rebuilt indexes using the following code:
(Note: this is v7 code)
// Get the search index
foreach(SearchIndexInfo index in SearchIndexInfoProvider.GetSearchIndexes(null,null))
if (index != null)
// Create rebuild task
SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Rebuild, index.IndexType, null, index.IndexName);
If you are creating the index and then rebuilding all in the same automated process, it's possible that the creation is not finished before the rebuild is execute. Seeing how a large index may take some time to create, this would probably result in an error. You would need to call the rebuild after the the creation process is completed.
If you are executing the rebuild after you know the index has been created, can you provide the stack trace or other details from the error?