How to Load Word Documents in .NET
How to Load Word Documents in .NET
Aspose.Words FOSS for .NET reads a document into memory as soon as you construct a Document object — every load path in the library funnels through Document’s constructor overloads and the LoadOptions class. This guide shows how to load a document from a file or a stream, supply a password or format-specific settings, and control what happens when loading encounters an external resource or a document that might be malformed. Aspose.Words FOSS for .NET is built from source and referenced directly in a project rather than installed from a package feed — see the Installation guide for build steps before working through the tasks below.
Step-by-Step Guide
Step 1: Load a Document from a File or Stream
Document has five constructors. Document() creates a new, empty document rather than loading one. Document(fileName) loads directly from a path on disk, and Document(stream) loads from any readable Stream — useful when the source isn’t a file, such as content already in memory or received over a network connection. Both have a companion overload that accepts a second argument, Document(fileName, loadOptions) and Document(stream, loadOptions), which is the entry point for every other task in this guide.
Step 2: Load a Password-Protected Document
Construct a LoadOptions with the password before calling Document(fileName, loadOptions) (or the stream overload). new LoadOptions(password) sets LoadOptions.Password directly; alternatively, set Password on a parameterless LoadOptions() instance before passing it in. Supply the password up front rather than loading first and reacting to a failure — Aspose.Words FOSS for .NET needs the password to parse a protected file at all, so there’s no partially loaded state to recover from.
Step 3: Apply Format-Specific Options for Text and Markdown Sources
Plain-text and Markdown sources accept settings the base LoadOptions doesn’t expose. TxtLoadOptions adds AutoNumberingDetection and DetectNumberingWithWhitespaces for recognizing numbered lists in plain text, DetectHyperlinks for turning bare URLs into hyperlinks, DocumentDirection (LeftToRight, RightToLeft, or Auto) for text flow direction, and separate LeadingSpacesOptions/TrailingSpacesOptions (of type TxtLeadingSpacesOptions/TxtTrailingSpacesOptions) for whitespace handling at the start and end of each line. MarkdownLoadOptions adds PreserveEmptyLines, ImportUnderlineFormatting, and SoftLineBreakCharacter for controlling how Markdown’s line-break conventions map onto paragraphs and runs. Both subclasses derive from LoadOptions, so a password or resource-loading callback set on either behaves the same as on the base class — pass the format-specific instance to Document(fileName, loadOptions) exactly as you would a plain LoadOptions.
Step 4: Redirect or Intercept External Resources During Loading
Set LoadOptions.ResourceLoadingCallback to an implementation of IResourceLoadingCallback when you need to control how an external resource referenced by the document is resolved while loading. Its ResourceLoading(args) method receives a ResourceLoadingArgs describing the resource’s ResourceType (Image, Font, CssStyleSheet, or Document) along with Uri and OriginalUri, and returns a ResourceLoadingAction — Default to load the resource normally, Skip to omit it, or UserProvided to substitute data supplied through ResourceLoadingArgs.SetData(data).
Step 5: Set Language Defaults and Recovery Behavior
When a document’s language metadata is missing or unreliable, set LoadOptions.LanguagePreferences.DefaultEditingLanguage to an EditingLanguage value before loading, and use AddEditingLanguage(language) or AddEditingLanguages(languages) on LanguagePreferences to register additional languages the document may contain. For sources that might be malformed, set LoadOptions.RecoveryMode to a DocumentRecoveryMode value — None to load without any recovery attempt, or TryRecover to have the loader work around some structural problems instead of failing the load outright.
Common Issues and Fixes
Loading a password-protected document still throws an exception after supplying a password.
Confirm the password was set on the exact LoadOptions instance passed to Document(fileName, loadOptions) (or the stream overload) — via new LoadOptions(password) or by setting Password afterward — and that this is the object actually passed to the constructor. A LoadOptions that was created but never handed to Document has no effect on the load.
Text or Markdown-specific settings don’t seem to apply.
Check that a TxtLoadOptions or MarkdownLoadOptions instance — not the base LoadOptions — was passed to the Document constructor. Only the subclass exposes the format-specific properties; passing the base class compiles but silently drops them.
External resources aren’t being intercepted or redirected.
ResourceLoadingCallback must be set on the same LoadOptions object passed to the Document constructor, and it must be assigned before the load call. Assigning it after loading has already completed has no effect.
A malformed document still fails to load after setting RecoveryMode.
DocumentRecoveryMode.TryRecover lets the loader work around some structural problems in a document, but more severe corruption can still prevent the document from loading successfully.
A document loaded from a Stream behaves differently than the same file loaded by path.
Verify the stream’s position is at the start before passing it to Document(stream) or Document(stream, loadOptions) — a stream left partway through its content loads only the remaining bytes.
Frequently Asked Questions
How do I load a document without any special options?
Pass a file path or a Stream directly to Document(fileName) or Document(stream) — LoadOptions is only required when a password, format-specific settings, or a callback is needed.
What’s the difference between LoadOptions, TxtLoadOptions, and MarkdownLoadOptions?
TxtLoadOptions and MarkdownLoadOptions both derive from LoadOptions and add settings specific to plain-text and Markdown sources respectively. Every general LoadOptions property — password, encoding, callbacks — remains available on either subclass.
Can I load a document directly from a byte array?
Wrap the bytes in a MemoryStream and pass that stream to Document(stream) or Document(stream, loadOptions) — there’s no constructor that accepts a byte array directly.
How do I control what happens when the loader can’t resolve an external resource?
Implement IResourceLoadingCallback and assign it to LoadOptions.ResourceLoadingCallback. Return ResourceLoadingAction.Skip from ResourceLoading(args) to omit the resource instead of letting the load fail.
Does setting RecoveryMode change how a well-formed document loads?
No. DocumentRecoveryMode only changes behavior when the loader actually encounters structural problems — a well-formed document loads the same way regardless of the setting.