Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
2.4k views
in SharePoint Server by 22 23 29

Hot to get SharePoint Root Site Collection URL using C# in Visual WebPart. I need to access a list in the Root Site Collection not, the current site URL without setting the URL as plain text, How I can do that?

using(SPSite oSite = new SPSite("Root Site Collection")) {  
                using(SPWeb oWeb = oSite.RootWeb)   
                {  
                    SPList oList = oWeb.Lists["Employee"];  
                    SPListItem oSPListItem = oList.Items.Add();  
                    oSPListItem["EmployeID"] = txtEmployeeId.Text;  
                    oSPListItem["City"] = txtCity.Text;  
                    oSPListItem.Update();  
                }  
            }

1 Answer

2 like 0 dislike
by 163 203 401
selected by
 
Best answer

How to get Root Site Collection URL in SharePoint using C#?

In Visual WebPart, to get the root site collection URL in SharePoint Server using C#, you have to use SPContext.Current.Site.Url as the following:

string currentSiteURL = Microsoft.SharePoint.SPContext.Current.Site.Url;

Example:
If you added your Visual WebPart in a page (http://debug/site1/Pages/ContactUs.aspx) at a SubSite (http://debug/site1) under the SharePoint Root Site URL is http://debug/, the SPContext.Current.Site.Url will get the root site collection URL (http://debug/)

In your code, you have to use SPContext.Current.Site.Url as below

using(SPSite oSite = new SPSite(SPContext.Current.Site.Url)) {  
  using(SPWeb oWeb = oSite.Open())   
      {  
             //Your Code
       }  
   }  

See also, How to get the current site URL in SharePoint using C#?

If you don’t ask, the answer is always NO!
...