How to Open a SharePoint Website with the Help of C# Code

In this blog, I am going to show how we can open a SharePoint website with the help of C# code And how we can access list, folder, file etc of a website.

This is the code which help us to open a website :

using (SPSite site = new SPSite(<Your SharePoint Site URL>))
{
      using(SPWeb web = site.OpenWeb())
      {
         //Your Code...
      }

}

If you want to access list of a web site then use below code :

using (SPWeb web = SPContext.Current.Site.OpenWeb("Your SharePoint Site URL "))
        {
            string MylistName = "YourListName";
            var lists = web.Lists;
            foreach (SPList list in lists)
            {
                if (list.Title.Equals(MylistName))
                    output.Write("<b>This list exists</b>");
            }

        }

If you want to authenticate your SharePoint through C# code then use below code :

var mytoken = SPSite.RootWeb.EnsureUser("usernameToImpersonate").UserToken;
        using (SPSite site = new SPSite(mytoken, this.ListAddress))
        {
            using (SPWeb web = site.OpenWeb())
            {
                // now your code here will be executed as selected user
            }

        }

Backup/Restore of SharePoint 2010 site Collection 


For Backup

Backup-SPSite -Identity http://localhost:1000 "c:\backup\MySpSitefile.bak"

For Restore
Restore-SPSite -Identity http://localhost::2000 -Path "c:\backup\
MySpSitefile.bak" -force

Ebook Download
View all
Learn
View all