Solved

Writing an xml file

Posted on 2011-09-15
8
235 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
  • 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
 

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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

706 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now