File being used by another process c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    File being used by another process c#

    I am trying to append to an .xml file using the code[1] below, but I keep coming across the error[2]. Any idea what could be causing it? Thanks.

    [1]
    Code:
            private bool insertName()
            {
                try
                {
                    XmlDocument XmlDoc = new XmlDocument();
                    XmlDoc.Load(XmlFilePath);
                    XmlElement NameElement = XmlDoc.CreateElement("name");
                    XmlText UserName = XmlDoc.CreateTextNode("Jemima");
                    NameElement.AppendChild(UserName);
                    XmlDoc.Save(XmlFilePath); // line 69
    
                    return true;
                }
                catch (Exception Excep)
                {
                    MessageBox.Show(Excep.ToString());
                    return false;
                }
            }
    [2]
    Code:
    System.IO.IOException: The process cannot access the file 'C:\Users\Chris\Documents\Visual Studio 2008\Projects\name\name\bin\Debug\names.xml' because it is being used by another process.
       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 System.Xml.XmlDocument.Save(String filename)
       at WindowsFormsApplication1.nameCheck.insertName() in C:\Users\Chris\Documents\Visual Studio 2008\Projects\name\name\name.cs:line 69
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Maybe you cannot save() to the same place you load()? (That seems silly to me, but maybe?)
    If it bugs you, get a copy of ProcessExplorer from the windows developement section and do a search for the filename, it will list all the processes that have a handle open to that file

    Comment

    • Markus
      Recognized Expert Expert
      • Jun 2007
      • 6092

      #3
      Originally posted by Plater
      Maybe you cannot save() to the same place you load()? (That seems silly to me, but maybe?)
      If it bugs you, get a copy of ProcessExplorer from the windows developement section and do a search for the filename, it will list all the processes that have a handle open to that file
      Might be silly, but it seems true: I changed the Save() path and it worked, although there was nothing appended to the file. Seems I need help my .xml stuff.

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        OK, here's something to try.

        .Load is overloaded, so instead of providing a filename, provide a FileStream object. Here's the gist (slightly modified to fit my test environment)
        Code:
        System.IO.FileStream fs = new System.IO.FileStream(@"c:\dev\forum.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
        XmlDocument XmlDoc = new XmlDocument();
        XmlDoc.Load(fs);
        fs.Close();
        XmlElement NameElement = XmlDoc.CreateElement("Forum");
        XmlDoc.DocumentElement.AppendChild(NameElement);
        fs = new System.IO.FileStream(@"c:\dev\forum.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
        XmlDoc.Save(fs); // line 69
        Notice how we close the FileStream. That should make sure that the file is available for writing.

        Also, notice that in your code you're never modifying the original XmlDocument. In my code, I say XmlDoc.Document Element.AppendC hild(NameElemen t) to actually append that name element into the document.

        One more suggestion. When you are debugging, comment out your try/catch, so that you not only get the error message, you can get the line number and stack trace.

        Comment

        • Markus
          Recognized Expert Expert
          • Jun 2007
          • 6092

          #5
          Thanks, Curt. But now the error has moved to the FileStream fs line.

          Error:
          sers\Chris\Docu ments\Visual Studio 2008\Projects\n ame\name\bin\De bug\names.xml' because it is being used by another process.
          at System.IO.__Err or.WinIOError(I nt32 errorCode, String maybeFullPath)
          at System.IO.FileS tream.Init(Stri ng path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIB UTES secAttrs, String msgPath, Boolean bFromProxy)
          at System.IO.FileS tream..ctor(Str ing path, FileMode mode, FileAccess access)
          at WindowsFormsApp lication1.nameC heck.insertName () in C:\Users\Chris\ Documents\Visua l Studio 2008\Projects\n ame\name\name.c s:line 64
          Code:
          FileStream fs = new FileStream(@XmlFilePath, FileMode.Open, FileAccess.ReadWrite); // line 64
                          XmlDocument XmlDoc = new XmlDocument();
                          XmlDoc.Load(fs);
                          fs.Close();
                          XmlElement NameElement = XmlDoc.CreateElement("Forum");
                          XmlDoc.DocumentElement.AppendChild(NameElement);
                          fs = new FileStream(@XmlFilePath, FileMode.Open, FileAccess.ReadWrite);
                          XmlDoc.Save(fs);

          Comment

          • Plater
            Recognized Expert Expert
            • Apr 2007
            • 7872

            #6
            Is that file used anywhere else?
            Such as possibly being constantly updated by some other process?
            Is this happening on a webpage? Each webpage will roughly "spawn a thread" so you could get race conditions with threads

            Comment

            • Curtis Rutland
              Recognized Expert Specialist
              • Apr 2008
              • 3264

              #7
              Do you have this file open by any other program? Do you have this file open anywhere else in the program that gets called before this method? Because your original code worked for me, actually. You need to find out what is actually locking this file. Because if something in your earlier code is locking it, you would still be able to load from it, all that requires is read access. When you try to gain write access by saving it, it's erroring out.

              I don't think that .Load actually locks the file.

              Comment

              • Markus
                Recognized Expert Expert
                • Jun 2007
                • 6092

                #8
                Thanks for your patience.

                I call this method when the form is loaded, and it works with the xml file (creating it). Could that be the problem?

                Code:
                private void nameCheck_Load(object sender, EventArgs e)
                        {
                            // need to check if the xml file exists
                            // if not: create it
                            XmlFilePath = Path.GetFullPath("names.xml");
                            if(File.Exists(XmlFilePath))
                            {
                                MessageBox.Show(XmlFilePath + " exists");
                            }
                            else
                            {
                                MessageBox.Show("names.xml doesn't exist -- creating now -- ");
                                nameInput.Text = Path.GetFullPath("names.xml");
                                XmlTextWriter Writer = new XmlTextWriter(XmlFilePath, System.Text.Encoding.UTF8);
                                Writer.WriteStartDocument();
                                Writer.Formatting = Formatting.Indented;
                                //Writer.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                                Writer.WriteStartElement("names");
                                    Writer.WriteStartElement("name");
                                    Writer.WriteValue("Mark");
                                    Writer.WriteEndElement();
                                Writer.WriteEndElement();
                                Writer.Close();
                            }
                
                        }

                Comment

                • roquen
                  New Member
                  • Mar 2010
                  • 1

                  #9
                  Hey guys,
                  I realise that I is kinda late, but still better late than never. I was having simila problem recently. I used XMLWriter to subsequently update xml file and was recieving the same errors. I found the clean solution for this:

                  The XMLWriter uses underlaying FileStream to access the modified file. Problem is that when you call XMLWriter.close () method, the underlaying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter with settings and specify that you need that underlaying stream closed.
                  example:

                  XMLWriterSettin gs settings = new Settings();
                  settings.CloseO utput = true;
                  XMLWriter writer = new XMLWriter(filep ath, settings);

                  Hope it helps

                  Comment

                  Working...