TextRange.Save Метод

Определение

Сохраняет текущее выделение в указанном формате данных из указанного потока.

Перегрузки

Save(Stream, String)

Сохраняет текущее выделение в указанном формате данных из указанного потока.

Save(Stream, String, Boolean)

Сохраняет текущее выделение в указанный поток в указанном формате данных с возможностью сохранения пользовательских объектов TextElement.

Save(Stream, String)

Сохраняет текущее выделение в указанном формате данных из указанного потока.

public:
 void Save(System::IO::Stream ^ stream, System::String ^ dataFormat);
public void Save (System.IO.Stream stream, string dataFormat);
member this.Save : System.IO.Stream * string -> unit
Public Sub Save (stream As Stream, dataFormat As String)

Параметры

stream
Stream

Пустой записываемый поток для сохранения текущего выделения.

dataFormat
String

Формат данных, в котором требуется сохранить текущее выделение. Текущие поддерживаемые форматы данных включают Rtf, Text, Xaml и XamlPackage.

Исключения

Параметр stream или dataFormat имеет значение null.

Указанный формат данных не поддерживается.

или

Содержимое, загруженное из stream, не соответствует указанному формату данных.

Примеры

В следующем примере иллюстрируется использование метода Save.

// This method accepts an input stream and a corresponding data format.  The method
// will attempt to load the input stream into a TextRange selection, apply Bold formatting
// to the selection, save the reformatted selection to an alternat stream, and return 
// the reformatted stream.  
Stream BoldFormatStream(Stream inputStream, string dataFormat)
{
    // A text container to read the stream into.
    FlowDocument workDoc = new FlowDocument();
    TextRange selection = new TextRange(workDoc.ContentStart, workDoc.ContentEnd);
    Stream outputStream = new MemoryStream();

    try
    {
        // Check for a valid data format, and then attempt to load the input stream
        // into the current selection.  Note that CanLoad ONLY checks whether dataFormat
        // is a currently supported data format for loading a TextRange.  It does not 
        // verify that the stream actually contains the specified format.  An exception 
        // may be raised when there is a mismatch between the specified data format and 
        // the data in the stream. 
        if (selection.CanLoad(dataFormat))
            selection.Load(inputStream, dataFormat);
    }
    catch (Exception e) { return outputStream; /* Load failure; return a null stream. */ }

    // Apply Bold formatting to the selection, if it is not empty.
    if (!selection.IsEmpty)
        selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

    // Save the formatted selection to a stream, and return the stream.
    if (selection.CanSave(dataFormat))
        selection.Save(outputStream, dataFormat);

    return outputStream;
}
' This method accepts an input stream and a corresponding data format.  The method
' will attempt to load the input stream into a TextRange selection, apply Bold formatting
' to the selection, save the reformatted selection to an alternat stream, and return 
' the reformatted stream.  
Private Function BoldFormatStream(ByVal inputStream As Stream, ByVal dataFormat As String) As Stream
    ' A text container to read the stream into.
    Dim workDoc As New FlowDocument()
    Dim selection As New TextRange(workDoc.ContentStart, workDoc.ContentEnd)
    Dim outputStream As Stream = New MemoryStream()

    Try
        ' Check for a valid data format, and then attempt to load the input stream
        ' into the current selection.  Note that CanLoad ONLY checks whether dataFormat
        ' is a currently supported data format for loading a TextRange.  It does not 
        ' verify that the stream actually contains the specified format.  An exception 
        ' may be raised when there is a mismatch between the specified data format and 
        ' the data in the stream. 
        If selection.CanLoad(dataFormat) Then
            selection.Load(inputStream, dataFormat)
        End If
    Catch e As Exception ' Load failure return a null stream. 
        Return outputStream
    End Try

    ' Apply Bold formatting to the selection, if it is not empty.
    If Not selection.IsEmpty Then
        selection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold)
    End If

    ' Save the formatted selection to a stream, and return the stream.
    If selection.CanSave(dataFormat) Then
        selection.Save(outputStream, dataFormat)
    End If

    Return outputStream
End Function

Комментарии

При возврате stream этого метода остается открытым, а текущая позиция в ней stream не определена.

В рамках операции сохранения содержимое текущего выделенного фрагмента может быть преобразовано в формат данных, заданный параметром dataFormat.

См. также раздел

Применяется к

Save(Stream, String, Boolean)

Сохраняет текущее выделение в указанный поток в указанном формате данных с возможностью сохранения пользовательских объектов TextElement.

public:
 void Save(System::IO::Stream ^ stream, System::String ^ dataFormat, bool preserveTextElements);
public void Save (System.IO.Stream stream, string dataFormat, bool preserveTextElements);
member this.Save : System.IO.Stream * string * bool -> unit
Public Sub Save (stream As Stream, dataFormat As String, preserveTextElements As Boolean)

Параметры

stream
Stream

Пустой записываемый поток для сохранения текущего выделения.

dataFormat
String

Формат данных, в котором требуется сохранить текущее выделение. Текущие поддерживаемые форматы данных включают Rtf, Text, Xaml и XamlPackage.

preserveTextElements
Boolean

true для сохранения пользовательских объектов TextElement, противном случае false.

Исключения

Происходит, когда stream или dataFormat имеет значение null.

Происходит, когда указанный формат данных не поддерживается. Может быть также вызван, если содержимое, загруженное из stream, не соответствует указанному формату данных.

Комментарии

Если preserveTextElements имеет значение false, пользовательские TextElement объекты сохраняются как известные TextElement типы. Например, предположим, что вы создали пользовательский TextElement с именем Heading1, который наследуется от Paragraph. При вызове этого метода с preserveTextElements значением false, Heading1 при сохранении TextRange преобразуется в Paragraph . При вызове этого метода с заданным preserveTextElements значением trueHeading1 сохраняется без преобразования. Чтобы сохранить пользовательские текстовые элементы, dataFormat необходимо задать значение DataFormats.Xaml.

Save(Stream, String, Boolean)представлен в платформа .NET Framework версии 3.5. Дополнительные сведения см. в статье Версии и зависимости платформы .NET Framework.

Применяется к