I am trying to open a Word file开发者_StackOverflow社区 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
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.
Try to set the FileShare
to ReadWrite
. Word has most likely a lock on the file which prevents you from locking it.
精彩评论