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


ServerDocument.Document - свойство

Возвращает массив байтов документа в памяти, загруженного в ServerDocument.

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

Синтаксис

'Декларация
Public ReadOnly Property Document As Byte()
    Get
public byte[] Document { get; }

Значение свойства

Тип: array<System.Byte[]
Возвращает массив байтов документа в памяти, загруженного в ServerDocument.

Исключения

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

Документ закрыт.

Заметки

Это свойство возвращает заполненный массив байтов, если ServerDocument был создан с помощью конструктора ServerDocument(array<Byte[], String), в котором есть параметр массива байтов, или конструктора ServerDocument(Stream, String) с параметром Stream. В противном случае это свойство возвращает пустой массив параметров.

Использование этого свойства позволяет вносить изменения в документ и отправлять его на клиентский компьютер без необходимости записи документа на диск.

Примеры

В следующем примере кода для создания нового объекта ServerDocument из массива байтов, содержащего рабочую книгу Excel с расширением имени файла XLSX, используется конструктор ServerDocument(array<Byte[], String). Затем в примере для отображения количества байтов в документе используется свойство Document.

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

  • Проект консольного приложения или другой проект, не связанный с 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 CreateServerDocumentFromByteArray(ByVal documentPath As String)
    Dim runtimeVersion As Integer = 0
    Dim serverDocument1 As ServerDocument = Nothing
    Dim stream As System.IO.FileStream = Nothing

    Try
        runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath)
        If runtimeVersion = 3 Then
            ' Read the file into a byte array.
            stream = New System.IO.FileStream(documentPath, System.IO.FileMode.Open, _
                System.IO.FileAccess.Read)
            Dim buffer(Fix(stream.Length)) As Byte
            stream.Read(buffer, 0, Fix(buffer.Length))

            ' Display the number of bytes in the document.
            serverDocument1 = New ServerDocument(buffer, "*.xlsx")
            MessageBox.Show("The Document property contains " & _
                serverDocument1.Document.Length.ToString() & " bytes.")
        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
        If Not (stream Is Nothing) Then
            stream.Close()
        End If
    End Try
End Sub
private void CreateServerDocumentFromByteArray(string documentPath)
{
    int runtimeVersion = 0;
    ServerDocument serverDocument1 = null;
    System.IO.FileStream stream = null;

    try
    {
        runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath);
        if (runtimeVersion == 3)
        {
            // Read the file into a byte array.
            stream = new System.IO.FileStream(
                documentPath, System.IO.FileMode.Open,
                System.IO.FileAccess.Read);
            byte[] buffer = new byte[(int)stream.Length];
            stream.Read(buffer, 0, (int)buffer.Length);

            // Display the number of bytes in the document.
            serverDocument1 = new ServerDocument(buffer,
                "*.xlsx");
            MessageBox.Show("The Document property contains " +
                serverDocument1.Document.Length.ToString() +
                " bytes.");
        }
    }
    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();
        if (stream != null)
            stream.Close();
    }
}

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

См. также

Ссылки

ServerDocument Класс

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