Cause: Recently wrote a script about the archive to a game on unity, using XML. And then found every time the file is saved, that is, call the Xmldocument.save () object method when the error will be said that the file path sharing abnormal what I do not remember. And then a half-day, no fruit. The reason for guessing may be that the file is occupied, simplifying the code to reproduce the exception in the new solution.
Run an error, line 33rd, "The file is being used by another process, so the process cannot access the file." ”
Find the answer online, this anomaly online also has the answer, although their code is not XML-related but the same error principle.
The reason for the error is that the file is being called by stream. To save/close a file, you must first close the stream.
So I added a sentence after reading the 22nd line of files
1 Reader. Close ();
Turn off the stream after reading the file. Run again, the "Save successfully" is displayed, and the XML file has indeed been modified.
The following is a complete code of the changes
1 usingSystem;2 usingSystem.Xml;3 4 namespaceXMLTest5 {6 classMyxmlreader7 {8 PublicXmlDocument Doc;9 Public stringPath;Ten PublicXmlReader Reader; One A PublicMyxmlreader (stringpath) - { -Path =path; theDoc =NewXmlDocument (); -XmlReaderSettings setting =Newxmlreadersettings (); -Setting. Ignorecomments =true; -Reader =xmlreader.create (Path, setting); + doc.load (reader); - Reader. Close (); + } A at PublicXmlNodeList getnodelist () - { -XmlElement root =doc.documentelement; - returnRoot. ChildNodes; - } - in Public voidSavedoc (stringpath) - { to doc.save (path); + } - } the * class Program $ {Panax Notoginseng Static voidMain (string[] args) - { the stringPath =@"F:\c#\xmltest\xmltest\newone.xml"; +Myxmlreader myreader =NewMyxmlreader (path); AXmlNodeList NodeList =myreader.getnodelist (); thenodelist[1]. attributes["name"]. Value ="ADSCHBGDSC"; + Myreader.savedoc (path); -Console.Write ("Save successfully"); $ Console.readkey (); $ } - } -}
About file save/close times wrong: The file is being used by another process, so the process cannot access the file.