Solved

Writing an xml file

Posted on 2011-09-15
8
237 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
WPF - Tooltips for ComboBox items 5 75
Convert an ASPX page into PDF 7 32
Help with AsEnumerable(), LINQ 4 42
Sql server, import complete table, using vb.net 9 36
Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

831 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