Friday, January 21, 2011

SharePoint 2010: Adding taxonomy field to files in a Document Library

Pre-requisite is that a taxonomy structure is set up with a "Term Group" group, a child "Term Set" with a "Term Name" term on it. Other than that, it's just about adapting site and list names to your deployment.

Here's the code:

        private void Test()
{
// get doc lib
SPWebApplication wa = SPWebApplication.Lookup(new Uri("http://server"));
SPSite site = wa.Sites["/sites/test"];
SPDocumentLibrary dl = site.RootWeb.Lists["DocumentLibrary1"] as SPDocumentLibrary;

// get taxonomy field
TaxonomySession session = new TaxonomySession(site, false);
TermSet set = session.DefaultSiteCollectionTermStore.sGroups["Term Group"].TermSets["Term Set"];
Term term = set.GetTerms("Term Name", 1033, false)[0];
TaxonomyField tf = dl.Fields["Term Field"] as TaxonomyField;

// add files
for (int i = 0; i < 100; i++)
{
using (FileStream fs = (new FileInfo(@"C:\Content.txt")).OpenRead())
{
// add item
string name = "Name " + i;
Hashtable ht = new Hashtable();
SPFile file = dl.RootFolder.Files.Add(name, fs, ht, true);
SPListItem item = file.Item;

// set item's taxonomy field value
tf.SetFieldValue(item, term);
item.Update();

// progress
Console.WriteLine("{0} created", name);
}
}
}

1 comment:

Gabriel Renom said...

Beautiful post!!!, you inspire me and save me more than 8h of work.

Keep publishing.