Archive

Archive for April, 2017

Programmatically Creating Site Backup in SharePoint

April 29, 2017 Leave a comment

Hello all,

try this example to Create Site Backup in SharePoint from Code


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SiteBackUp
{
public class SiteBackup
{
static void Main(string[] args)
{
siteBackup("http://servername:portnumber","SharePointSiteBackup");
}
public static void siteBackup(string siteURL,string fileName)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using(SPSite objSite=new SPSite(siteURL))
{
using(SPWeb objWeb=objSite.OpenWeb())
{
bool currentSiteStatus=objSite.AllowUnsafeUpdates;
objSite.AllowUnsafeUpdates=true;
bool currentWebStatus=objWeb.AllowUnsafeUpdates;
objWeb.AllowUnsafeUpdates=true;
string comment = objWeb.Title+"- Creating Backup is completed";
SPSiteCollection siteCollection=objSite.WebApplication.Sites;
objSite.ReadOnly=true;
string time=DateTime.Now.ToString("dd-MM-yyyy");
string backupName= "D:\\SiteBackup\\Backup" + fileName+"_"+time+".bak";
siteCollection.Backup(siteURL,backupName,false);
objSite.AllowUnsafeUpdates=currentSiteStatus;
objWeb.AllowUnsafeUpdates=currentWebStatus;
if(objSite.ReadOnly==true)
{
objSite.ReadOnly=false;
siteBackupLog(comment);
}
}
}
});
}
catch (Exception ex)
{
SPSite site = new SPSite(siteURL);
if (site.ReadOnly == true)
site.ReadOnly = false;
siteBackupLog(ex.Message);
}
}

public static void siteBackupLog(string message)
{
string PathName = "C:\\SiteBackup logs\\";
PathName = PathName + "Backuplog-" + DateTime.Now.ToString("dd-MM-yyyy") + ".log";
StreamWriter sw = new StreamWriter(PathName, true);
sw.WriteLine(message + " - " + DateTime.Now);
sw.Flush();
sw.Close();
}
}
}

Good Luck

Categories: SharePoint 2010