Поделиться через


ServerDocument.Save - метод

Сохраняет все изменения документа с помощью класса ServerDocument.

Пространство имен:  Microsoft.VisualStudio.Tools.Applications
Сборка:  Microsoft.VisualStudio.Tools.Applications.ServerDocument (в Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll)

Синтаксис

'Декларация
Public Sub Save
public void Save()

Исключения

Исключение Условие
DocumentClosedException

Объект ServerDocument закрыт.

MissingHostItemIdException

Свойство Id класса CachedDataHostItem имеет значение nullпустая ссылка (Nothing в Visual Basic) или является пустым.

MissingDataIdException

Свойство Id класса CachedDataItem имеет значение nullпустая ссылка (Nothing в Visual Basic) или является пустым.

MissingTypeException

Свойство DataType класса CachedDataItem имеет значение nullпустая ссылка (Nothing в Visual Basic) или является пустым.

Заметки

Метод Save сохраняет любые изменения кэшированных данных или URL-адреса манифеста развертывания в документе. Если объект ServerDocument создан с помощью документа, находящегося на диске, то этот метод сохраняет изменения на диске. Если объект ServerDocument создан с помощью документа, находящегося в памяти, то этот метод сохраняет изменения в буфере памяти.

Примеры

В следующем примере кода создается новый ServerDocument для указанной рабочей книги Excel, методом SerializeDataInstance изменяется строка, кэшированная в книге, а затем с помощью метода Save выполняется сохранение измененной строки.

Для этого примера требуется:

  • Настройки уровня документа для Excel, которая содержит класс Sheet1 в пространстве имен ExcelWorkbook1 и кэшированную строку в классе Sheet1 с именем CachedString.

  • Проект консольного приложения или другой проект, не связанный с Office.

  • Ссылки на следующие сборки:

    • Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll и Microsoft.VisualStudio.Tools.Applications.Runtime.dll (если проект предназначен для платформы .NET Framework 4).

      или

    • Microsoft.VisualStudio.Tools.Applications.ServerDocument.v10.0.dll и Microsoft.VisualStudio.Tools.Applications.Runtime.v9.0.dll (если проект предназначен для платформы .NET Framework 3.5).

  • Операторы Imports (для Visual Basic) или using (для C#) для пространств имен Microsoft.VisualStudio.Tools.Applications и Microsoft.VisualStudio.Tools.Applications.Runtime вверху вашего файла с кодом.

Private Sub ModifyCachedString(ByVal documentPath As String)
    Dim runtimeVersion As Integer = 0
    Dim serverDocument1 As ServerDocument = Nothing

    Try
        runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath)
        If runtimeVersion <> 3 Then
            MessageBox.Show("This document does not have a Visual Studio Tools for Office " & _
                "customization, or it has a customization that was created with a version of " & _
                "the runtime that is incompatible with this version of the ServerDocument class.")
            Return
        End If

        If ServerDocument.IsCacheEnabled(documentPath) Then
            serverDocument1 = New ServerDocument(documentPath)
            Dim hostItem1 As CachedDataHostItem = _
                serverDocument1.CachedData.HostItems("ExcelWorkbook1.Sheet1")
            Dim dataItem1 As CachedDataItem = hostItem1.CachedData("CachedString")

            If dataItem1 IsNot Nothing AndAlso _
                Type.GetType(dataItem1.DataType).Equals(GetType(String)) Then

                dataItem1.SerializeDataInstance("This is the new cached string value.")
                serverDocument1.Save()
            End If
        Else
            MessageBox.Show("The specified document does not have cached data.")
        End If

    Catch ex As System.IO.FileNotFoundException
        System.Windows.Forms.MessageBox.Show("The specified document does not exist.")
    Catch ex As UnknownCustomizationFileException
        System.Windows.Forms.MessageBox.Show("The specified document has a file " & _
            "extension that is not supported by Visual Studio Tools for Office.")
    Finally
        If Not (serverDocument1 Is Nothing) Then
            serverDocument1.Close()
        End If
    End Try
End Sub
private void ModifyCachedString(string documentPath)
{
    int runtimeVersion = 0;
    ServerDocument serverDocument1 = null;

    try
    {
        runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath);

        if (runtimeVersion != 3)
        {
            MessageBox.Show("This document does not have a Visual Studio Tools for " +
                "Office customization, or it has a customization that was created with " +
                "a version of the runtime that is incompatible with this version of the " +
                "ServerDocument class.");
            return;
        }

        if (ServerDocument.IsCacheEnabled(documentPath))
        {
            serverDocument1 = new ServerDocument(documentPath);
            CachedDataHostItem hostItem1 = 
                serverDocument1.CachedData.HostItems["ExcelWorkbook1.Sheet1"];
            CachedDataItem dataItem1 = hostItem1.CachedData["CachedString"];

            if (dataItem1 != null &&
                Type.GetType(dataItem1.DataType) == typeof(string))
            {
                dataItem1.SerializeDataInstance("This is the new cached string value.");
                serverDocument1.Save();
            }
        }
        else
        {
            MessageBox.Show("The specified document does not have cached data.");
        }
    }
    catch (System.IO.FileNotFoundException)
    {
        System.Windows.Forms.MessageBox.Show("The specified document does not exist.");
    }
    catch (UnknownCustomizationFileException)
    {
        System.Windows.Forms.MessageBox.Show("The specified document has a file " +
            "extension that is not supported by Visual Studio Tools for Office.");
    }
    finally
    {
        if (serverDocument1 != null)
            serverDocument1.Close();
    }
}

Безопасность платформы .NET Framework

См. также

Ссылки

ServerDocument Класс

Microsoft.VisualStudio.Tools.Applications - пространство имен