C #: opening a Word file in FileStream for reading when it is open in Word

I am trying to open a Word file for reading using FileStream in C #. I hacked a quickfetch application consisting of a text box and a button to start creating a stream. The sample code to open the file is as follows:

if (File.Exists(this.TxtPath.Text)) { Stream s = new FileStream(this.TxtPath.Text, FileMode.Open, FileAccess.Read, FileShare.Read); } 

When I try to open a Word file that is already open in Word, I get a System.IO.Exception message saying that the file is already open by another process and cannot be opened.

When I try to open the same file in Notepad ++, when it is open in Word, it works without problems. Therefore, in principle, this should be possible.

Is there something I forgot?

Quick edit: I use Word 2007 and VisualStudio 2008 if that helps. Version .NET Framework 3.5.

+4
source share
2 answers

Try FileShare.ReadWrite . The explanation at http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx implies that using FileShare.Read conflicts with other processes trying to write.

+8
source

Try setting FileShare to ReadWrite . Word most likely locks the file, which prevents you from locking it.

+2
source

All Articles