How to Open MS Word file for read-only

When I use Aspose.Words to open a Word document that is currently open in Microsoft Word, it throws an exception.

Certainly, if I would want to modify the file, it would not make sense to open it if it is already open in MS Word. However, often I just want to open a file for reading, and this should not interfere with an already-open instance of the file. That is, I’d like a way to open a DOC or DOCX file as “ReadOnly”, such that Aspose will read in the full data of the file, without needing to obtain write-access to the file.

Is this possible in the current version of Aspose.Words? If not, would it be possible to add this functionality please?

Hi Avi,

Thanks for your inquiry. When you open a document with Microsoft Word application, it locks the document for editing and when you try to load the same document into Aspose.Words’ DOM, it throws the following exception:

System.IO.IOException: The process cannot access the file 'C:\Temp\...' because it is being used by another process.*

To workaround this you can load the document using a stream and specify FileShare parameter which allows you to open the file even when it’s locked for editing. Please see the code below:

// The specified file can be opened in MS Word when opening it with Aspose.Words here.
string fileName = @"C:\Temp\in.docx";
// Open the document.
FileStream docStream = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// Create Aspose.Words Document from stream
Document doc = new Document(docStream);
// Close stream
docStream.Close();
// Do something with the document.
// Save the document.
doc.Save(@"C:\Temp\out.pdf");

Best regards,

1 Like

Thanks! This worked perfectly. This was very helpful.