TextRange.Load Method (Stream, String)


Loads the current selection in a specified data format from a specified stream.

Namespace:   System.Windows.Documents
Assembly:  PresentationFramework (in PresentationFramework.dll)

public void Load(
	Stream stream,
	string dataFormat


Type: System.IO.Stream

A readable stream that contains data to load into the current selection.

Type: System.String

A data format to load the data as. Currently supported data formats are Rtf, Text, Xaml, and XamlPackage.

Exception Condition

Occurs when stream or dataFormat is null.


Occurs when the specified data format is unsupported. May also be raised if content loaded from stream does not match the specified data format.

If CanSeek is true for stream, content will be loaded from the beginning of the stream to the end of the stream. Otherwise, content will be read from the current Position to the end of the stream. When this method returns, stream is left open, and the current position within stream is undefined.

A load operation replaces the current selection with the newly loaded content.

The following example demonstrates the use of the Load method.

// 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();

        // 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;

.NET Framework
Available since 3.0
Return to top