Document(Stream) Constructor

Opens an existing document from a stream. Automatically detects the file format.

Namespace:  Aspose.Words
Assembly:  Aspose.Words (in Aspose.Words.dll) Version: 20.9.0

Syntax

public Document(
	Stream stream
)

Parameters

stream
Type: System.IOStream
Stream where to load the document from.

Exceptions

ExceptionCondition
UnsupportedFileFormatExceptionThe document format is not recognized or not supported.
FileCorruptedExceptionThe document appears to be corrupted and cannot be loaded.
ExceptionThere is a problem with the document and it should be reported to Aspose.Words developers.
IOExceptionThere is an input/output exception.
IncorrectPasswordExceptionThe document is encrypted and requires a password to open, but you supplied an incorrect password.
ArgumentNullExceptionThe stream cannot be null.
NotSupportedExceptionThe stream does not support reading or seeking.
ObjectDisposedExceptionThe stream is a disposed object.

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Examples

Shows how to load a document using a stream.
using (Stream stream = File.OpenRead(MyDir + "Document.docx"))
{
    Document doc = new Document(stream);

    Assert.AreEqual("Hello World!", doc.GetText().Trim());
}
Shows how to load a document from a URL.
// Create a URL that points to a Microsoft Word document.
const string url = "https://omextemplates.content.office.net/support/templates/en-us/tf16402488.dotx";

// Download the document into a byte array, then load that array into a document using a memory stream.
using (WebClient webClient = new WebClient())
{
    byte[] dataBytes = webClient.DownloadData(url);

    using (MemoryStream byteStream = new MemoryStream(dataBytes))
    {
        Document doc = new Document(byteStream);

        // At this stage, we can read and edit the document's contents and then save it to the local file system.
        Assert.AreEqual("Use this section to highlight your relevant passions, activities, and how you like to give back. " +
                        "It’s good to include Leadership and volunteer experiences here. " +
                        "Or show off important extras like publications, certifications, languages and more.",
            doc.FirstSection.Body.Paragraphs[4].GetText().Trim());

        doc.Save(ArtifactsDir + "Document.LoadFromWeb.docx");
    }
}

See Also