Solved

Writing an xml file

Posted on 2011-09-15
8
240 Views
Last Modified: 2012-05-12
I create the xml file and that part works fine. I read the xml file ok but then when I try to write to it again I get a enrror indicating that it is still in use even though I closed the xmltextreader object.

Error:


System.IO.IOException was unhandled
  Message="The process cannot access the file 'M:\Projects\C3Wizard\C3Wizard\bin\Debug\C3.xml' because it is being used by another process."
  Source="mscorlib"
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
       at System.Xml.XmlTextWriter..ctor(String filename, Encoding encoding)
       at C3Wizard.frmDBLocation.btnOK_Click(Object sender, EventArgs e) in M:\Projects\C3Wizard\C3Wizard\frmDBLocation.vb:line 38
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at C3Wizard.mdiMain.DatabaseToolStripMenuItem_Click(Object sender, EventArgs e) in M:\Projects\C3Wizard\C3Wizard\mdiMain.vb:line 149
       at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
       at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
       at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
       at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
       at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
       at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
       at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
       at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ToolStrip.WndProc(Message& m)
       at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at C3Wizard.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:


Attached is my code for writing the xml followed by my code to read the xml file.


Dim origPath$, newPath$
        Dim writer As New Xml.XmlTextWriter("C3.xml", System.Text.Encoding.UTF8)

        origPath = thePath
        newPath = ""

        FILE_NAME = System.AppDomain.CurrentDomain.BaseDirectory & "C3.xml"

        If rdoLocal.Checked = True Then
            ofdOpenFile.FileName = System.AppDomain.CurrentDomain.BaseDirectory & "C3dbase.mdb"
        Else
            ofdOpenFile.FileName = txtPath.Text
        End If

        myStream = ofdOpenFile.OpenFile()
        If Not (myStream Is Nothing) Then

            Try
                'Dim stream_writer As New IO.StreamWriter(FILE_NAME, False)

                Try

                    newPath = ofdOpenFile.FileName

                    writer.WriteStartDocument(True)
                    writer.Formatting = Xml.Formatting.Indented
                    writer.Indentation = 2
                    writer.WriteStartElement("Path")
                    writer.WriteStartElement("Location")
                    writer.WriteString(System.IO.Path.GetDirectoryName(ofdOpenFile.FileName))
                    writer.WriteEndElement()
                    writer.WriteStartElement("DBname")
                    writer.WriteString(ofdOpenFile.SafeFileName)
                    writer.WriteEndElement()
                    'writer.WriteString(newPath)
                    writer.WriteEndElement()
                    writer.WriteEndDocument()
                    'writer.Close()
                    'stream_writer.Write("Path = " & newPath)
            Finally
                    ' stream_writer.Close()
                End Try
            Catch exc As Exception
                ' Report all errors.
                MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " & _
                    "Error")
            End Try

            myStream.Close()
        End If

        writer.Close()

        If newPath <> origPath Then sCheckIfEmptyDB(newPath) : thePath = newPath

Open in new window

Dim FILE_NAME As String

        FILE_NAME = System.AppDomain.CurrentDomain.BaseDirectory & "C3.xml"

        If System.IO.File.Exists(FILE_NAME) = True Then

            Dim MyFile = New XmlTextReader(FILE_NAME)

            MyFile.WhiteSpaceHandling = WhitespaceHandling.None
            MyFile.Read()
            MyFile.Read()

            If Not MyFile.EOF Then

                MyFile.GetAttribute("Path")
                MyFile.Read()

                thePath = MyFile.ReadElementString("Location") & "\" & MyFile.ReadElementString("DBname")

            End If

            'close the reader
            MyFile.Close()

        Else

            frmDBLocation.ShowDialog()

        End If

Open in new window

0
Comment
Question by:SheldonC
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 22

Expert Comment

by:plusone3055
ID: 36543109
0
 

Author Comment

by:SheldonC
ID: 36543183
The second link was one of the links that I used as reference to develop my code and I cant access the demo or source in the other link.
0
 
LVL 40
ID: 36543265
Nothing evident at first sight.

Are you sure that the file is not opened somewhere else in the application? What happens in ofdOpenFile? Could txtPath.Text be the same file?

Have you tried putting a breakpoint on line 52 to make sure that it is called? A step by step run might lead you to the problem.

Does this happens while debugging. If you stop the execution of the application while debugging, it is possible that you do not hit line 52.
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:SheldonC
ID: 36543586
I get the error in the write routine when I declare the xmltextwriter object

Dim writer As New Xml.XmlTextWriter("C3.xml", System.Text.Encoding.UTF8)

I have no problem creating the file initially using the same code but after I create the file, I can read it fine, however if I go back to my write routine after reading the file I get the error on the line where I declare the xmltextwriter
0
 
LVL 40

Accepted Solution

by:
Jacques Bourgeois (James Burger) earned 250 total points
ID: 36543958
In see nothing that could cause the problem in the code presented.

Search for the file name in your solution. You probably open it somewhere else and forget to close it there.
0
 

Author Comment

by:SheldonC
ID: 36544485
The code I am showing you are the only two places where reference the xml file. I use it to store the location of the database file.
0
 
LVL 40
ID: 36544716
You do not specify the path for "C3.xml", which means that it is probably written in the application directory.

This is not a good place to put a file that needs to be written to, because the places where we run an application have security restrictions when the user is not an administrator. This might be your problem.

The best place to store a file that will need to be written to by the application is in a subdirectory in the Application Data directory. It's name can change in different versions of Windows, but you can retrieve it with the following command.
System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Open in new window

I would try to save "C3.xml" in there to see if it solves the problem.
0
 

Author Closing Comment

by:SheldonC
ID: 36545125
lol I am such an idiot...thanks. I found another reference to the file that needed to be closed.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question