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

Hot to get current SharePoint site URL in Visual WebPart using C#?, I need to replace this URL with the current SharePoint Site URL? How I can do that?

using(SPSite oSite = new SPSite("http://test:1512")) {  
                using(SPWeb oWeb = oSite.RootWeb)   
                    SPList oList = oWeb.Lists["Employee"];  
                    SPListItem oSPListItem = oList.Items.Add();  
                    oSPListItem["EmployeID"] = txtEmployeeId.Text;  
                    oSPListItem["City"] = txtCity.Text;  

1 Answer

1 like 0 dislike
by 155 174 353
selected by
Best answer

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

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

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

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.Web.Url will get the current subSite URL (http://debug/site1)

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

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

See also, How to get Root site Collection URL in SharePoint using C#?

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