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


ServerDocument - конструктор (array<Byte[], String)

Инициализирует новый экземпляр класса ServerDocument с помощью массива байтов, который представляет документ, который требуется загрузить, а также расширение файла документа.

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

Синтаксис

'Декларация
Public Sub New ( _
    bytes As Byte(), _
    fileType As String _
)
public ServerDocument(
    byte[] bytes,
    string fileType
)

Параметры

  • bytes
    Тип: array<System.Byte[]
    Массив байтов, представляющий документ, который требуется загрузить.
  • fileType
    Тип: System.String
    Перед расширением имени файла документа, сохраняемого в параметре bytes, должна стоять точка (.) — например, ".xlsx" или ".docx".

Исключения

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

Параметр bytes имеет значение nullпустая ссылка (Nothing в Visual Basic) или пуст.

– или –

Параметр fileType равен nullпустая ссылка (Nothing в Visual Basic), пуст или содержит только пробелы.

UnknownCustomizationFileException

Параметр fileType задает расширение имени файла, которое не поддерживается средой Среда выполнения Visual Studio Tools for Office.

DocumentCustomizedWithPreviousRuntimeException

Файл, указанный параметром documentPath, содержит настройку, которая не была создана с помощью Visual Studio 2010 Tools для среды выполнения Office или Visual Studio Tools для системы Microsoft Office (версия среды выполнения 3.0).

Заметки

Этот конструктор используется для получения доступа к кэшированным данным или данным манифеста развертывания в документе, находящемся в памяти. При использовании этого конструктора документ открывается с правом доступа на чтение/запись.

Параметр fileType используется только для определения типа документа, который хранится в массиве данных. Значение fileType сопоставляется с одним из типов файлов, которые поддерживаются настройками уровня документов. Попытка открытия файла не предпринимается. При необходимости можно передавать полное имя файла (например, "Workbook1.xlsx"); однако при этом используется только расширение имени файла. Дополнительные сведения о поддерживаемых типах файлов см. в разделе Архитектура настроек на уровне документа.

Для получения доступа к массиву байтов, чтобы получить документ после вызова этого конструктора, следует использовать свойство Document.

Примеры

В следующем примере кода для создания нового объекта 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 Класс

ServerDocument - перегрузка

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