Create Top Navigation menu programatically


In my previous post, I wrote about creating Quick Launch navigation programmatically.
In this post, I will show how to create Top Navigation programmatically. It is easy since
the code is almost the same as for Quick Launch.

Top Navigation is navigation located on the top of the screen and it is important part of
almost every SharePoint site (marked in red square on the image). 


SharePoint Top Navigation



The code is very simple, it consists of reading the Top Navigation object and deleting the
existing links in it. And then, after the existing Top Navigation is cleared, putting the new
links which we have read from some text file.

C# CODE: 


SPSecurity.RunWithElevatedPrivileges(delegate()
{
     using (SPSite oSiteCollection = new SPSite("http://mySiteUrl"))
     {
           using (SPWeb oWeb = oSiteCollection.OpenWeb())
           {
             // Create the nod
    SPNavigationNodeCollection _topNav = oWeb.Navigation.TopNavigationBar;
          // Delete all existing items in Top Navigation
          int _counter = 0;
          while (_topNav.Count != _counter && _topNav.Count > 0)
          {
              _counter++;
              SPNavigationNode _item = _topNav[0];
              _item.Delete();
          }

      // Here we read links that will go in Top Navigation from text file
      // Let's say that in "abc.txt" file we have links written as (title|link):
      //    
      // My project |/sites/MyTestSite1
      // Project documents|/sites/MyDocLib2
      // Reports|/sites/MyCustomReports
      //...
   
      string _line;
      System.IO.StreamReader _file = new System.IO.StreamReader("abc.txt");
      while ((_line = _file.ReadLine()) != null)
       {
        string[] _splitStr = _line.Split('|'); 
        string _title = _splitStr[0];
        string _url = _splitStr[1];

     SPNavigationNode _SPNode = new SPNavigationNode(_title, _url, true);
  
              _topNav.AddAsLast(_SPNode);
               } 
              _file.Close();
           }
     }
});