Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Opening a Word File in a FileStream for reading while it is opened in Word

I am trying to open a Word file for reading using a FileStream in C#. I hacked a quick sample application which consists of a textfield and a button to trigger the creation of the stream. The sample Code to open the file is the following:

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 opened in Word I get a System.IO.Exception which states that the file is already opened by another process and can't be opened.

When I try to open the same file in Notepad++ while it is opened in Word it works problem free. So basically it should be possible.

Is there anything I overlooked?

Quick edit: I'm using Word 2007 and VisualStudio 2008 if this helps. .NET Framework Version is 3.5

like image 596
Aurril Avatar asked Dec 28 '22 07:12

Aurril


1 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.

like image 67
Steven Sudit Avatar answered Jan 23 '23 14:01

Steven Sudit