0

I'm trying to lock an XML file for write access while it's opened in my program. My program uses an XmlDataProvider. I can't find a way to accomplish both:

Partial Class MainWindow

  'XmlData As XmlDataProvider - Declared in MainWindow.xaml
  Private m_FileName As String = Nothing
  Private m_FileNumber As Integer


  Public Sub OpenFile(fileName As String)
    If m_FileName IsNot Nothing Then CloseFile()

    m_FileName = fileName
    m_FileNumber = FreeFile
    FileOpen(m_FileNumber, m_FileName, OpenMode.Binary, OpenAccess.Default, OpenShare.LockWrite)
    XmlData.Source = New Uri(m_FileName)
    ' IOException: The process cannot access the file "C:\path\filename.xml" because it is already in use by a different process.
    ' I translated the error message, I hope you know which one I mean.
  End Sub

  Public Sub CloseFile()
    If m_FileName Is Nothing Then Exit Sub

    XmlData.Source = Nothing
    FileClose(m_FileNumber)
    m_FileName = Nothing
  End Sub
End Class

I also cannot find a way to tell the XmlDataProvider to lock the file for me. What can I do?

LWChris
  • 3,320
  • 1
  • 22
  • 39
  • I would say (for this moment) that you are locking yourself out. Can you tell the definition of `XmlData`? – Styxxy Sep 19 '13 at 23:02
  • @Styxxy XmlData is an XmlDataProvider declared in MainWindow.xaml (as commented above in the code). In XAML, that is `` within the `` node ("default.xml" content is just the XML declaration and ``). The code-behind assigns a new source and binding does the rest to visualize and edit the file contents. – LWChris Nov 18 '13 at 23:26
  • I assume the `XmlDataProvider` can't load a locked file (although I don't quite understand why it says 'locked by a different process'; it may be a different thread - but should be the same process, shouldn't it?). I can't swap the statements because then I'd process the XML file before locking it which means it could be in use while I'm processing it. On the other hand, I can't find a way to pass a locked file to the `XmlDataProvider` nor do I know how to tell the provider to automatically lock files whilst they are used as source. – LWChris Nov 18 '13 at 23:41

0 Answers0