ServerDocument Конструкторы
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Перегрузки
| ServerDocument(String) |
Инициализирует новый экземпляр класса ServerDocument, используя полный путь к документу, который требуется загрузить. |
| ServerDocument(Byte[], String) |
Инициализирует новый экземпляр класса ServerDocument с помощью массива байтов, который представляет документ, который требуется загрузить, а также расширение файла документа. |
| ServerDocument(Stream, String) |
Инициализирует новый экземпляр класса ServerDocument с помощью потока, который представляет документ, который требуется загрузить, а также расширение файла документа. |
| ServerDocument(String, FileAccess) |
Инициализирует новый экземпляр класса ServerDocument с помощью полного пути к документу, который требуется загрузить, а также значения, обозначающего доступ к файлу документа. |
ServerDocument(String)
Инициализирует новый экземпляр класса ServerDocument, используя полный путь к документу, который требуется загрузить.
public ServerDocument (string documentPath);
Параметры
- documentPath
- String
Полный путь к документу, который требуется загрузить.
Исключения
Параметр documentPath равен null, пуст или содержит только пробелы.
Файл, указанный параметром documentPath, не существует.
Файл, указанный параметром documentPath, содержит настройку, которая не была создана с помощью набора средств Visual Studio 2010 для Office Runtime или набора средств Visual Studio для системы Microsoft Office (версия среды выполнения 3.0).
Файл, заданный параметром documentPath, имеет расширение, не поддерживаемое средой Набор средств Visual Studio для Office (cреда выполнения).
Примеры
В следующем примере кода конструктор используется ServerDocument(String) для создания нового ServerDocument , который загружает указанный документ. Затем в примере отображается URL-адрес манифеста развертывания для настройки, прикрепленной к документу.
Для этого примера требуются:
Проект консольного приложения или другой проект, не относящийся к Office.
Ссылки на следующие сборки:
Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll и Microsoft.VisualStudio.Tools.Applications.Runtime.dll (если проект предназначен для платформы .NET Framework 4 или .NET Framework 4.5).
or
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 void CreateServerDocumentFromPath(string documentPath)
{
int runtimeVersion = 0;
ServerDocument serverDocument1 = null;
try
{
runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath);
if (runtimeVersion == 3)
{
serverDocument1 = new ServerDocument(documentPath);
MessageBox.Show("The URL of the deployment manifest is: \n" +
serverDocument1.DeploymentManifestUrl.ToString());
}
}
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();
}
}
Private Sub CreateServerDocumentFromPath(ByVal documentPath As String)
Dim runtimeVersion As Integer = 0
Dim serverDocument1 As ServerDocument = Nothing
Try
runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath)
If runtimeVersion = 3 Then
serverDocument1 = New ServerDocument(documentPath)
MessageBox.Show("The URL of the deployment manifest is: " & vbLf & _
serverDocument1.DeploymentManifestUrl.ToString())
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
Комментарии
Используйте этот конструктор для доступа к кэшированным данным или сведениям манифеста развертывания в документе, расположенном на диске. При использовании этого конструктора указанный документ открывается с доступом на чтение и запись.
Применяется к
ServerDocument(Byte[], String)
Инициализирует новый экземпляр класса ServerDocument с помощью массива байтов, который представляет документ, который требуется загрузить, а также расширение файла документа.
public ServerDocument (byte[] bytes, string fileType);
Параметры
- bytes
- Byte[]
Массив байтов, представляющий документ, который требуется загрузить.
- fileType
- String
Перед расширением имени файла документа, сохраняемого в параметре bytes, должна стоять точка (.) — например ".xlsx" или ".docx".
Исключения
Параметр bytes имеет значение null или является пустым.
-или-
Параметр fileType равен null, пуст или содержит только пробелы.
Параметр fileType задает расширение имени файла, которое не поддерживается средой Набор средств Visual Studio для Office (cреда выполнения).
Файл, указанный параметром documentPath, содержит настройку, которая не была создана с помощью набора средств Visual Studio 2010 для Office Runtime или набора средств Visual Studio для системы Microsoft Office (версия среды выполнения 3.0).
Примеры
В следующем примере кода используется конструктор [ServerDocument (конструктор байтов) <xref:Microsoft.VisualStudio.Tools.Applications.ServerDocument.%23ctor%28System.Byte%5B%5D%2CSystem.String%29> для создания нового конструктора [ServerDocument (Byte <xref:Microsoft.VisualStudio.Tools.Applications.ServerDocument> из массива байтов, содержащего книгу Excel с расширением XLSX). Затем в примере используется конструктор [ServerDocument (свойство Byte <xref:Microsoft.VisualStudio.Tools.Applications.ServerDocument.Document%2A> для вывода числа байтов в документе).
Для этого примера требуются:
Проект консольного приложения или другой проект, не относящийся к Office.
Ссылки на следующие сборки:
Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll и Microsoft.VisualStudio.Tools.Applications.Runtime.dll (если проект предназначен для платформы .NET Framework 4 или .NET Framework 4.5).
or
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#) операторы [ServerDocument конструктор (Byte <xref:Microsoft.VisualStudio.Tools.Applications?displayProperty=fullName> и [ServerDocument- <xref:Microsoft.VisualStudio.Tools.Applications.Runtime?displayProperty=fullName> файл] в верхней части файла кода.
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();
}
}
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
Комментарии
Используйте этот конструктор для доступа к кэшированным данным или сведениям манифеста развертывания в документе, который уже находится в памяти. При использовании этого конструктора документ открывается с доступом на чтение и запись.
fileTypeПараметр используется только для определения типа документа, хранящегося в массиве байтов. Значение fileType сопоставляется с одним из типов файлов, поддерживаемых настройками на уровне документа. Попытка открыть файл не предпринималась. При необходимости можно передать полное имя файла (например, "Workbook1.xlsx"), но в этом случае будет использоваться только расширение имени файла. Дополнительные сведения о поддерживаемых типах файлов см. в разделе Архитектура настроек на уровне документа.
Чтобы получить доступ к массиву байтов для документа после вызова этого конструктора, используйте конструктор [ServerDocument (свойство Byte) <xref:Microsoft.VisualStudio.Tools.Applications.ServerDocument.Document%2A> .
Применяется к
ServerDocument(Stream, String)
Инициализирует новый экземпляр класса ServerDocument с помощью потока, который представляет документ, который требуется загрузить, а также расширение файла документа.
public ServerDocument (System.IO.Stream stream, string fileType);
Параметры
- stream
- Stream
Поток, представляющий документ, который требуется загрузить.
- fileType
- String
Перед расширением имени файла документа, сохраняемого в параметре bytes, должна стоять точка (.) — например ".xlsx" или ".docx".
Исключения
Параметр stream имеет значение null или является пустым.
-или-
Параметр fileType равен null, пуст или содержит только пробелы.
Параметр stream имеет нулевую длину или его текущее положение — в конце потока.
Параметр fileType задает расширение имени файла, которое не поддерживается средой Набор средств Visual Studio для Office (cреда выполнения).
Файл, указанный параметром documentPath, содержит настройку, которая не была создана с помощью набора средств Visual Studio 2010 для Office Runtime или набора средств Visual Studio для системы Microsoft Office (версия среды выполнения 3.0).
Примеры
В следующем примере кода конструктор используется ServerDocument(Stream, String) для создания нового объекта ServerDocument из FileStream , который содержит книгу Excel с расширением имени файла XLSX. Затем в коде отображается URL-адрес манифеста развертывания для настройки, прикрепленной к документу.
Для этого примера требуются:
Проект консольного приложения или другой проект, не относящийся к Office.
Ссылки на следующие сборки:
Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll и Microsoft.VisualStudio.Tools.Applications.Runtime.dll (если проект предназначен для платформы .NET Framework 4 или .NET Framework 4.5).
or
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 void CreateServerDocumentFromStream(string documentPath)
{
int runtimeVersion = 0;
ServerDocument serverDocument1 = null;
System.IO.FileStream stream = null;
try
{
runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath);
if (runtimeVersion == 3)
{
stream = new System.IO.FileStream(
documentPath, System.IO.FileMode.Open);
serverDocument1 = new ServerDocument(stream,
"*.xlsx");
MessageBox.Show("The URL of the deployment manifest is: \n" +
serverDocument1.DeploymentManifestUrl.ToString());
}
}
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();
}
}
Private Sub CreateServerDocumentFromStream(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
stream = New System.IO.FileStream(documentPath, System.IO.FileMode.Open)
serverDocument1 = New ServerDocument(stream, "*.xlsx")
MessageBox.Show("The URL of the deployment manifest is: " & vbLf & _
serverDocument1.DeploymentManifestUrl.ToString())
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
Комментарии
Используйте этот конструктор для доступа к кэшированным данным или сведениям манифеста развертывания в документе, который уже находится в памяти. При использовании этого конструктора документ открывается с доступом на чтение и запись.
fileTypeПараметр используется только для определения типа документа, хранящегося в массиве байтов. Значение fileType сопоставляется с одним из типов файлов, поддерживаемых настройками на уровне документа. Попытка открыть файл не предпринималась. При необходимости можно передать полное имя файла (например, "Workbook1.xlsx"), но в этом случае будет использоваться только расширение имени файла. Дополнительные сведения о поддерживаемых типах файлов см. в разделе Архитектура настроек на уровне документа.
Чтобы получить доступ к массиву байтов для документа после вызова этого конструктора, используйте Document свойство.
Применяется к
ServerDocument(String, FileAccess)
Инициализирует новый экземпляр класса ServerDocument с помощью полного пути к документу, который требуется загрузить, а также значения, обозначающего доступ к файлу документа.
public ServerDocument (string documentPath, System.IO.FileAccess access);
Параметры
- documentPath
- String
Полный путь к документу, который требуется загрузить.
- access
- FileAccess
Значение, указывающее доступ к файлу документа.
Исключения
Параметр documentPath равен null, пуст или содержит только пробелы.
Значение access — System.IO.FileAccess.Write.
Файл, указанный параметром documentPath, не существует.
В файле, заданном параметром documentPath, нет настройки, а значение access равно System.IO.FileAccess.Read.
Файл, указанный параметром documentPath, содержит настройку, которая не была создана с помощью набора средств Visual Studio 2010 для Office Runtime или набора средств Visual Studio для системы Microsoft Office (версия среды выполнения 3.0).
Файл, заданный параметром documentPath, имеет расширение, не поддерживаемое средой Набор средств Visual Studio для Office (cреда выполнения).
Примеры
В следующем примере кода конструктор используется ServerDocument(String, FileAccess) для создания нового ServerDocument , который загружает указанный документ с доступом только для чтения. Затем в коде отображается URL-адрес манифеста развертывания для настройки, прикрепленной к документу.
Для этого примера требуются:
Проект консольного приложения или другой проект, не относящийся к Office.
Ссылки на следующие сборки:
Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll и Microsoft.VisualStudio.Tools.Applications.Runtime.dll (если проект предназначен для платформы .NET Framework 4 или .NET Framework 4.5).
or
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 void CreateServerDocumentReadOnly(string documentPath)
{
int runtimeVersion = 0;
ServerDocument serverDocument1 = null;
try
{
runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath);
if (runtimeVersion == 3)
{
serverDocument1 = new ServerDocument(documentPath,
System.IO.FileAccess.Read);
MessageBox.Show("The URL of the deployment manifest is: \n" +
serverDocument1.DeploymentManifestUrl.ToString());
}
}
catch (System.IO.FileNotFoundException)
{
System.Windows.Forms.MessageBox.Show("The specified document does not exist.");
}
catch (DocumentNotCustomizedException)
{
System.Windows.Forms.MessageBox.Show("The specified document does not " +
"have a customization.");
}
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();
}
}
Private Sub CreateServerDocumentReadOnly(ByVal documentPath As String)
Dim runtimeVersion As Integer = 0
Dim serverDocument1 As ServerDocument = Nothing
Try
runtimeVersion = ServerDocument.GetCustomizationVersion(documentPath)
If runtimeVersion = 3 Then
serverDocument1 = New ServerDocument(documentPath, System.IO.FileAccess.Read)
MessageBox.Show("The URL of the deployment manifest is: " & vbLf & _
serverDocument1.DeploymentManifestUrl.ToString())
End If
Catch ex As System.IO.FileNotFoundException
System.Windows.Forms.MessageBox.Show("The specified document does not exist.")
Catch ex As DocumentNotCustomizedException
System.Windows.Forms.MessageBox.Show("The specified document does not " & _
"have a customization.")
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
Комментарии
Используйте этот конструктор для доступа к кэшированным данным или сведениям манифеста развертывания в документе, расположенном на диске, если необходимо открыть документ с доступом только для чтения или только для записи. По умолчанию другие ServerDocument конструкторы открывают документ с доступом на чтение и запись.