tags:

views:

364

answers:

3

Currently I have a C# application that reads an XML file. But if this XML file is opened in word and then my application reads the same XML file, I get an IO Exception. All I need to do is read the file. Here is a small code snippet;

public Object Load()
{
  try
  {
    using (FileStream fs = new FileStream(
       filePath,
       FileMode.Open,
       FileAccess.Read,
       FileShare.ReadWrite)) // Also tried, FileShare.Read and gets the same exception
    {
       return ((FooObject) new XmlSerializer(typeof(FooObject))
                .Deserialize(fs)) as Object;
    }
  }
  catch (Exception ex)
  {
    LogException(ex);
    return null;
  }
}
+1  A: 

Word will definitely lock the file for writing, which will prevent your FileStream from opening. You're requesting ReadWrite access, which will fail.

I believe you can open it for read, though - just change your line to:

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))

Note the FileShare.Read vs. FileShare.ReadWrite. I don't believe word opens files for exclusive access - but it does lock writing.

Reed Copsey
I have tried this and I get the same Exception.
arc1880
Word has the file locked exclusively. To do this, you'll need to open up the file before you open it in Word. There will be no way to read it otherwise.
Reed Copsey
If the file is opened by Word, is it possible to make a copy of the file and then just read the copy? Or will word prevent the copying of the file?
arc1880
A: 

You can't do anything if word has opened the file exclusively and I think this is the case.

Catch the exception and inform your user he might need to end Word to make your application work properly.

edit

Word do not open the file exclusively - make sure you open the file for reading onky - check out the code from other commenter.

devdimi
A: 

I created a quick WinForms application based on the MSDN Docs for XmlSerializer.Deserialize(). Using the same FileStream arguments as you I had no problems opening the file, even if it was already open in Word. Do you think the value of the 'filePath' may be incorrect somehow ie trying adding something like the following to Object_Load():

if (!File.Exists(filePath))
{
    throw new FileNotFoundException("File does not exist", filePath);
}
Amal Sirisena