如何:以编程方式备份内容

上次修改时间: 2010年11月4日

适用范围: SharePoint Foundation 2010

本主题说明如何对 SharePoint Foundation 内容组件的备份进行编程。本主题假定您已熟悉在 SharePoint Foundation 中备份和还原数据概述使用 SharePoint Foundation 备份/还原对象模型进行编程

内容组件备份

  1. 向 Visual Studio 项目中添加对 Microsoft.SharePoint 的引用,并向代码文件中添加用于 Microsoft.SharePoint.Administration 和 Microsoft.SharePoint.Administration.Backup 命名空间的 using 语句。

  2. 在 Main 方法内,提示用户指定应将备份存储到的位置。

    Console.Write("Enter full UNC path to the directory where the backup will be stored:");
    String backupLocation = Console.ReadLine();
    
    Console.Write("Enter full UNC path to the directory where the backup will be stored:")
    Dim backupLocation As String = Console.ReadLine()
    
  3. 在 Main 方法中,通过使用静态 GetBackupSettings 方法来创建 SPBackupSettings 对象。对于第一个参数,传递应存储备份的路径。对于第二个参数,传递 SPBackupMethodType 值之一的字符串版本

    SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
    
    Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
    
  4. 提示用户指定要备份的内容组件并将其名称分配给 IndividualItem 属性。若要查看场中可作为备份操作对象的组件名称的详细列表,可以在服务器命令行上运行命令 stsadm -o backup -showtree,也可以访问管理中心应用程序中的"操作">"执行备份"。若要指定整个场,请将"Farm"用作名称。(若将此属性设置为 null,则也会选择整个场来进行备份,并按常理假定您在所有后续代码中会使用 IndividualItem 来按名称标识要备份的组件。有关示例,请参阅步骤 8 中对 FindItems() 方法的使用。)

    Console.Write("Enter name of component to backup (default is whole farm):");
    settings.IndividualItem = Console.ReadLine();
    
    Console.Write("Enter name of component to backup (default is whole farm):")
    settings.IndividualItem = Console.ReadLine()
    
  5. (可选)设置一个或多个 IsVerboseUpdateProgressBackupTheads() 属性。(有关这些属性的详细信息,请参阅相关的参考主题。)

    settings.IsVerbose = true;
    settings.UpdateProgress = 10;
    settings.BackupThreads = 2;
    
    settings.IsVerbose = True
    settings.UpdateProgress = 10
    settings.BackupThreads = 2
    
  6. 使用 CreateBackupRestore() 方法创建备份操作。(同时还会创建此操作的历史记录对象。有关详细信息,请参阅 SPBackupRestoreHistoryObjectSPBackupRestoreHistoryList。)

    Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
    
    Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
    
  7. 如果用户界面要求用户键入一个组件名称而不是从列表中选取一个组件名称,则您必须确保输入的名称与某个组件的名称完全匹配。向 Main 方法中添加以下行。

    SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
    
    Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
    
  8. 添加以下 EnsureUniqueValidComponentName 方法的实现。使用 FindItems() 方法可检索其名称与用户输入的名称完全匹配的内容对象的集合。如果未找到匹配项,则提示用户重试。如果找到多个匹配项,则提示用户输入更加具体的信息。如果用户输入的组件名称明确而有效,则会获取对表示用户要还原的组件的 SPBackupRestoreObject 对象的引用。

    private static SPBackupRestoreObject EnsureUniqueValidComponentName(SPBackupRestoreSettings settings, ref Guid operationGUID)
    {
        SPBackupRestoreObjectCollection list = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem);
        SPBackupRestoreObject component = null;
    
        if (list.Count <= 0)
        {
            Console.WriteLine("There is no component with that name. Run again with a new name.");
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
        else if (list.Count > 1)  // The component name specified is ambiguous. Prompt user to be more specific.
        {
            Console.WriteLine("More than one component matches the name you entered.");
            Console.WriteLine("Run again with one of the following:");
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine("\t{0}", list[i].ToString());
            }
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
        else
        {
            component = list[0];
        }
    
        return component;
    
    }
    
    Private Shared Function EnsureUniqueValidComponentName(ByVal settings As SPBackupRestoreSettings, ByRef operationGUID As Guid) As SPBackupRestoreObject
        Dim list As SPBackupRestoreObjectCollection = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem)
        Dim component As SPBackupRestoreObject = Nothing
    
        If list.Count <= 0 Then
            Console.WriteLine("There is no component with that name. Run again with a new name.")
            Console.WriteLine("Press Enter to continue.")
            Console.ReadLine()
        ElseIf list.Count > 1 Then ' The component name specified is ambiguous. Prompt user to be more specific.
            Console.WriteLine("More than one component matches the name you entered.")
            Console.WriteLine("Run again with one of the following:")
            For i As Integer = 0 To list.Count - 1
                Console.WriteLine(vbTab & "{0}", list(i).ToString())
            Next i
            Console.WriteLine("Press Enter to continue.")
            Console.ReadLine()
        Else
            component = list(0)
        End If
    
        Return component
    
    End Function
    
  9. 在 Main 方法中,创建一个 Boolean 标记和一个条件结构,前者指示是否有足够的空间供备份使用,而后者仅在 EnsureUniqueValidComponentName 方法返回一个有效节点后才会运行。

    Boolean targetHasEnoughSpace = false;
    if (node != null)
    {
        targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node);
    }
    
    Dim targetHasEnoughSpace As Boolean = False
    If node IsNot Nothing Then
        targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node)
    End If
    
  10. 添加以下 EnsureEnoughDiskSpace 方法的实现。使用 DiskSizeRequired() 方法可获取所需的空间量,而使用 DiskSize() 方法可确定目标磁盘上的可用空间量。

    private static Boolean EnsureEnoughDiskSpace(String ___location, Guid backup, SPBackupRestoreObject node)
    {
        UInt64 backupSize = SPBackupRestoreConsole.DiskSizeRequired(backup, node);
        UInt64 diskFreeSize = 0;
        UInt64 diskSize = 0;
        Boolean hasEnoughSpace = true;
    
        try
        {
            SPBackupRestoreConsole.DiskSize(___location, out diskFreeSize, out diskSize);
        }
        catch
        {
            diskFreeSize = diskSize = UInt64.MaxValue;
        }
    
        if (backupSize > diskFreeSize)
        {
            // Report through your UI that there is not enough disk space.
            Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, ___location, diskFreeSize);
            Console.WriteLine("Please try again with a different backup ___location or a smaller component.");
            hasEnoughSpace = false;
        }
        else if (backupSize == UInt64.MaxValue || diskFreeSize == 0)
        {
            // Report through your UI that it cannot be determined whether there is enough disk space.
            Console.WriteLine("Cannot determine if that ___location has enough disk space.");
            Console.WriteLine("Please try again with a different backup ___location or a smaller component.");
            hasEnoughSpace = false;
        }
        return hasEnoughSpace;
    
    }
    
    Private Shared Function EnsureEnoughDiskSpace(ByVal ___location As String, ByVal backup As Guid, ByVal node As SPBackupRestoreObject) As Boolean
        Dim backupSize As UInt64 = SPBackupRestoreConsole.DiskSizeRequired(backup, node)
        Dim diskFreeSize As UInt64 = 0
        Dim diskSize As UInt64 = 0
        Dim hasEnoughSpace As Boolean = True
    
        Try
            SPBackupRestoreConsole.DiskSize(___location, diskFreeSize, diskSize)
        Catch
            diskSize = UInt64.MaxValue
            diskFreeSize = diskSize
        End Try
    
        If backupSize > diskFreeSize Then
            ' Report through your UI that there is not enough disk space.
            Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, ___location, diskFreeSize)
            Console.WriteLine("Please try again with a different backup ___location or a smaller component.")
            hasEnoughSpace = False
        ElseIf backupSize = UInt64.MaxValue OrElse diskFreeSize = 0 Then
            ' Report through your UI that it cannot be determined whether there is enough disk space.
            Console.WriteLine("Cannot determine if that ___location has enough disk space.")
            Console.WriteLine("Please try again with a different backup ___location or a smaller component.")
            hasEnoughSpace = False
        End If
        Return hasEnoughSpace
    
    End Function
    
  11. 在 Main 方法中,创建一个条件结构,此结构仅在 EnsureEnoughDiskSpace 返回 true 时才会运行。

    if (targetHasEnoughSpace)
    {
        // TODO: Set the backup operation as the active operation
        // and run it.
    }
    
    If targetHasEnoughSpace Then
         ' TODO: Set the backup operation as the active operation
         ' and run it.
    End If
    
  12. 将上一步骤中的"TODO"行替换为以下代码。这会使用 SetActive() 方法将操作设置为活动操作,并进行测试以验证操作是否成功。如果操作失败(当另一个备份或还原操作正在进行时将出现此情况),则将向应用程序的用户界面报告错误。

    if (SPBackupRestoreConsole.SetActive(backup) == true)
    {
        // TODO: Run the operation. See next step.
    }
    else
    {
        // Report through your UI that another backup
        // or restore operation is underway. 
        Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.");
    }
    
    If SPBackupRestoreConsole.SetActive(backup) = True Then
         ' TODO: Run the operation. See next step.
    Else
         ' Report through your UI that another backup
         ' or restore operation is underway. 
         Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.")
    End If
    
  13. SetActive() 调用成功时将运行的代码分支中,使用 Run() 方法运行操作。检测操作是否成功。如果操作失败,则将操作失败的消息报告给用户界面。以下代码将替换上一步骤中的"TODO"行。

    if (SPBackupRestoreConsole.Run(backup, node) == false)
    {
        // Report "error" through your UI.
        String error = SPBackupRestoreConsole.Get(backup).FailureMessage;
        Console.WriteLine(error);
    }
    
    If SPBackupRestoreConsole.Run(backup, node) = False Then
       ' Report "error" through your UI.
       Dim [error] As String = SPBackupRestoreConsole.Get(backup).FailureMessage
       Console.WriteLine([error])
    End If
    
  14. 使用 Remove() 方法清除还原内容。将以下代码添加到在步骤 11 中插入的右大括号的紧前面。

    // Clean up the operation.
    SPBackupRestoreConsole.Remove(backup);
    
    Console.WriteLine("Backup attempt complete. Press Enter to continue.");
    Console.ReadLine();
    
    ' Clean up the operation.
    SPBackupRestoreConsole.Remove(backup)
    
    Console.WriteLine("Backup attempt complete. Press Enter to continue.")
    Console.ReadLine()
    

示例

下面的代码演示如何以编程方式备份内容组件。

using System;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Backup;

namespace MyCompany.SharePoint.Administration.Backup
{
    class Backup
    {
        static void Main(string[] args)
        {
            // Identify the ___location for the backup storage.
            Console.Write("Enter full UNC path to the directory where the backup will be stored:");
            String backupLocation = Console.ReadLine();
            
            // Create the backup settings.
            SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");

            // Identify the content component to backup.
            Console.Write("Enter name of component to backup (default is whole farm):");
            settings.IndividualItem = Console.ReadLine();
            
            // Set optional operation parameters.
            settings.IsVerbose = true;
            settings.UpdateProgress = 10;
            settings.BackupThreads = 10;

            // Create the backup operation and return its ID.
            Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);

            // Ensure that user has identified a valid and unique component.
            SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);

            // Ensure that there is enough space.
            Boolean targetHasEnoughSpace = false;
            if (node != null)
            {
                targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node);
            }

            // If there is enough space, attempt to run the backup.
            if (targetHasEnoughSpace)
            {
                // Set the backup as the active job and run it.
                if (SPBackupRestoreConsole.SetActive(backup) == true)
                {
                    if (SPBackupRestoreConsole.Run(backup, node) == false)
                    {
                        // Report "error" through your UI.
                        String error = SPBackupRestoreConsole.Get(backup).FailureMessage;
                        Console.WriteLine(error);
                    }
                }
                else
                {
                    // Report through your UI that another backup
                    // or restore operation is underway. 
                    Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.");
                }

                // Clean up the operation.
                SPBackupRestoreConsole.Remove(backup);

                Console.WriteLine("Backup attempt complete. Press Enter to continue.");
                Console.ReadLine();
            }
        }// end Main

        private static SPBackupRestoreObject EnsureUniqueValidComponentName(SPBackupRestoreSettings settings, ref Guid operationGUID)
        {
            SPBackupRestoreObjectCollection list = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem);
            SPBackupRestoreObject component = null;

            if (list.Count <= 0)
            {
                Console.WriteLine("There is no component with that name. Run again with a new name.");
                Console.WriteLine("Press Enter to continue.");
                Console.ReadLine();
            }
            else if (list.Count > 1)  // The component name specified is ambiguous. Prompt user to be more specific.
            {
                Console.WriteLine("More than one component matches the name you entered.");
                Console.WriteLine("Run again with one of the following:");
                for (int i = 0; i < list.Count; i++)
                {
                    Console.WriteLine("\t{0}", list[i].ToString());
                }
                Console.WriteLine("Press Enter to continue.");
                Console.ReadLine();
            }
            else
            {
                component = list[0];
            }

            return component;

        }// end EnsureUniqueValidComponentName

        private static Boolean EnsureEnoughDiskSpace(String ___location, Guid backup, SPBackupRestoreObject node)
        {
            UInt64 backupSize = SPBackupRestoreConsole.DiskSizeRequired(backup, node);
            UInt64 diskFreeSize = 0;
            UInt64 diskSize = 0;
            Boolean hasEnoughSpace = true;

            try
            {
                SPBackupRestoreConsole.DiskSize(___location, out diskFreeSize, out diskSize);
            }
            catch
            {
                diskFreeSize = diskSize = UInt64.MaxValue;
            }

            if (backupSize > diskFreeSize)
            {
                // Report through your UI that there is not enough disk space.
                Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, ___location, diskFreeSize);
                Console.WriteLine("Please try again with a different backup ___location or a smaller component.");
                hasEnoughSpace = false;
            }
            else if (backupSize == UInt64.MaxValue || diskFreeSize == 0)
            {
                // Report through your UI that it cannot be determined whether there is enough disk space.
                Console.WriteLine("Cannot determine if that ___location has enough disk space.");
                Console.WriteLine("Please try again with a different backup ___location or a smaller component.");
                hasEnoughSpace = false;
            }
            return hasEnoughSpace;

        }// end EnsureEnoughDiskSpace

    }// end Backup class
}// end namespace
Imports System
Imports Microsoft.SharePoint.Administration
Imports Microsoft.SharePoint.Administration.Backup

Namespace MyCompany.SharePoint.Administration.Backup
    Module Backup
        Sub Main(ByVal args() As String)
            ' Identify the ___location for the backup storage.
            Console.Write("Enter full UNC path to the directory where the backup will be stored:")
            Dim backupLocation As String = Console.ReadLine()

            ' Create the backup settings.
            Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")

            ' Identify the content component to backup.
            Console.Write("Enter name of component to backup (default is whole farm):")
            settings.IndividualItem = Console.ReadLine()

            ' Set optional operation parameters.
            settings.IsVerbose = True
            settings.UpdateProgress = 10
            settings.BackupThreads = 10

            ' Create the backup operation and return its ID.
            Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)

            ' Ensure that user has identified a valid and unique component.
            Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)

            ' Ensure that there is enough space.
            Dim targetHasEnoughSpace As Boolean = False
            If node IsNot Nothing Then
                targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node)
            End If

            ' If there is enough space, attempt to run the backup.
            If targetHasEnoughSpace Then
                ' Set the backup as the active job and run it.
                If SPBackupRestoreConsole.SetActive(backup) = True Then
                    If SPBackupRestoreConsole.Run(backup, node) = False Then
                        ' Report "error" through your UI.
                        Dim [error] As String = SPBackupRestoreConsole.Get(backup).FailureMessage
                        Console.WriteLine([error])
                    End If
                Else
                    ' Report through your UI that another backup
                    ' or restore operation is underway. 
                    Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.")
                End If

                ' Clean up the operation.
                SPBackupRestoreConsole.Remove(backup)

                Console.WriteLine("Backup attempt complete. Press Enter to continue.")
                Console.ReadLine()
            End If
        End Sub ' end Main

        Private Function EnsureUniqueValidComponentName(ByVal settings As SPBackupRestoreSettings, ByRef operationGUID As Guid) As SPBackupRestoreObject
            Dim list As SPBackupRestoreObjectCollection = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem)
            Dim component As SPBackupRestoreObject = Nothing

            If list.Count <= 0 Then
                Console.WriteLine("There is no component with that name. Run again with a new name.")
                Console.WriteLine("Press Enter to continue.")
                Console.ReadLine()
            ElseIf list.Count > 1 Then ' The component name specified is ambiguous. Prompt user to be more specific.
                Console.WriteLine("More than one component matches the name you entered.")
                Console.WriteLine("Run again with one of the following:")
                For i As Integer = 0 To list.Count - 1
                    Console.WriteLine(vbTab & "{0}", list(i).ToString())
                Next i
                Console.WriteLine("Press Enter to continue.")
                Console.ReadLine()
            Else
                component = list(0)
            End If

            Return component

        End Function ' end EnsureUniqueValidComponentName

        Private Function EnsureEnoughDiskSpace(ByVal ___location As String, ByVal backup As Guid, ByVal node As SPBackupRestoreObject) As Boolean
            Dim backupSize As UInt64 = SPBackupRestoreConsole.DiskSizeRequired(backup, node)
            Dim diskFreeSize As UInt64 = 0
            Dim diskSize As UInt64 = 0
            Dim hasEnoughSpace As Boolean = True

            Try
                SPBackupRestoreConsole.DiskSize(___location, diskFreeSize, diskSize)
            Catch
                diskSize = UInt64.MaxValue
                diskFreeSize = diskSize
            End Try

            If backupSize > diskFreeSize Then
                ' Report through your UI that there is not enough disk space.
                Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, ___location, diskFreeSize)
                Console.WriteLine("Please try again with a different backup ___location or a smaller component.")
                hasEnoughSpace = False
            ElseIf backupSize = UInt64.MaxValue OrElse diskFreeSize = 0 Then
                ' Report through your UI that it cannot be determined whether there is enough disk space.
                Console.WriteLine("Cannot determine if that ___location has enough disk space.")
                Console.WriteLine("Please try again with a different backup ___location or a smaller component.")
                hasEnoughSpace = False
            End If
            Return hasEnoughSpace

        End Function ' end EnsureEnoughDiskSpace

    End Module ' end Backup class
End Namespace ' end namespace

请参阅

任务

如何:以编程方式备份和还原单个网站集

如何:以编程方式还原内容

如何:创建可以备份和还原的内容类

如何:扩展 STSADM 实用工具

引用

Microsoft.SharePoint.Administration.Backup

Backup

Restore

概念

使用 SharePoint Foundation 备份/还原对象模型进行编程

其他资源

Stsadm.exe 命令行工具