how to close xmldocument in c# - c#

I created an application for Android in Xamarin.I open an xml file ,then I save the changes. I need to close it but xmldocument has not any option to do that.
How can I close the file? I really need to do this because on other activity I want to modify it and it says :"Sharing violation on path"

If you're using the XmlDocument.Save just put a using around the TextWriter should do it:
var doc = new XmlDocument();
var filePath = "myXmlFile.xml";
doc.Load(filePath);
using (var writer = new StreamWriter(filePath))
{
doc.Save(writer);
}

Related

How to save to the same file with XDocument?

I'm trying to edit xml file.
but document.Save() method has to use another file name.
Is there any way to use same file? or other method. Thank you!
string path = "test.xml";
using (FileStream xmlFile = File.OpenRead(path))
{
XDocument document = XDocument.Load(xmlFile);
var setupEl = document.Root;
var groupEl = setupEl.Elements().ElementAt(0);
var valueEl = groupEl.Elements().ElementAt(1);
valueEl.Value = "Test2";
document.Save("test-result.xml");
// document.Save("test.xml"); I want to use this line.
}
I receive the error:
The process cannot access the file '[...]\test.xml' because it is being used by another process.
The problem is that you are trying to write to the file while you still have it open. However, you have no need to have it open once you've loaded the XML file. Simply scoping your code more granularly will solve the issue:
string path = "test.xml";
XDocument document;
using (FileStream xmlFile = File.OpenRead(path))
{
document = XDocument.Load(xmlFile);
}
// the rest of your code

Issue with XmlDocument Open XML file directly after using throws exception

I have a strange issue with my XmlDocument class.
I write some XML file with it, which works great.
And I have Save() method:
public void Save()
{
var xwSettings = new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Indent = true,
IndentChars = "\t"
};
using (XmlWriter xw = XmlWriter.Create(new FileStream(this.FilePath, FileMode.Create), xwSettings))
{
XmlDocument.WriteTo(xw);
}
}
Like everyone sees, I'm using "using" which should give the xml free :)
But if I try to read this file directly after calling Save() I get the exception:
The process can not access the file "___.xml", because it's already in use by another process.
Can someone explain that to me and give me a solution for it?
Kind regards
You are not disposing your file stream. Try changing your code like this.
using (var xmlStream = new FileStream(this.FilePath, FileMode.Create))
{
using (XmlWriter xw = XmlWriter.Create(xmlStream, xwSettings))
{
var xDoc = new XmlDocument();
xDoc.WriteTo(xw);
}
}

Trying to Load an XML File Upon Form Load, Getting Error

In C# am trying to check to see if an XML file is created, if not create the file and then create the xml declaration, a comment and a parent node.
When I try to load it, it gives me this error:
"The process cannot access the file 'C:\FileMoveResults\Applications.xml' because it is being used by another process."
I checked the task manager to ensure it wasn't open and sure enough there were no open applications of it. Any ideas of what's going on?
Here is the code I am using:
//check for the xml file
if (!File.Exists(GlobalVars.strXMLPath))
{
//create the xml file
File.Create(GlobalVars.strXMLPath);
//create the structure
XmlDocument doc = new XmlDocument();
doc.Load(GlobalVars.strXMLPath);
//create the xml declaration
XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", null, null);
//create the comment
XmlComment xcom = doc.CreateComment("This file contains all the apps, versions, source and destination paths.");
//create the application parent node
XmlNode newApp = doc.CreateElement("applications");
//save
doc.Save(GlobalVars.strXMLPath);
Here is the code I ended up using to fix this issue:
//check for the xml file
if (!File.Exists(GlobalVars.strXMLPath))
{
using (XmlWriter xWriter = XmlWriter.Create(GlobalVars.strXMLPath))
{
xWriter.WriteStartDocument();
xWriter.WriteComment("This file contains all the apps, versions, source and destination paths.");
xWriter.WriteStartElement("application");
xWriter.WriteFullEndElement();
xWriter.WriteEndDocument();
}
File.Create() returns a FileStream that locks the file until it's closed.
You don't need to call File.Create() at all; doc.Save() will create or overwrite the file.
I would suggest something like this:
string filePath = "C:/myFilePath";
XmlDocument doc = new XmlDocument();
if (System.IO.File.Exists(filePath))
{
doc.Load(filePath);
}
else
{
using (XmlWriter xWriter = XmlWriter.Create(filePath))
{
xWriter.WriteStartDocument();
xWriter.WriteStartElement("Element Name");
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
}
//OR
XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", null, null);
XmlComment xcom = doc.CreateComment("This file contains all the apps, versions, source and destination paths.");
XmlNode newApp = doc.CreateElement("applications");
XmlNode newApp = doc.CreateElement("applications1");
XmlNode newApp = doc.CreateElement("applications2");
doc.Save(filePath); //save a copy
}
The reason your code is currently having problems is because of: File.Create creates the file and opens the stream to the file, and then you never make use of it (never close it) on this line:
//create the xml file
File.Create(GlobalVars.strXMLPath);
if you did something like
//create the xml file
using(Stream fStream = File.Create(GlobalVars.strXMLPath)) { }
Then you would not get that in use exception.
As a side note XmlDocument.Load will not create a file, only work with an already create one
You could create a stream, setting the FileMode to FileMode.Create and then use the stream to save the Xml to the path specified.
using (System.IO.Stream stream = new System.IO.FileStream(GlobalVars.strXMLPath, FileMode.Create))
{
XmlDocument doc = new XmlDocument();
...
doc.Save(stream);
}

Issue in XDocument.Save Method

I am trying to insert data in existing XMl file. I have the following code.
string file = MapPath("~/XMLFile1.xml");
XDocument doc;
//Verify whether a file is exists or not
if (!System.IO.File.Exists(file))
{
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("Contacts"));
}
else
{
doc = XDocument.Load(file);
}
foreach (var c in MyContactsLst)
{
//var contactsElement = new XElement("Contacts",
var contactsElement = new XElement("Contact",
new XElement("Name", c.FirstOrDefault().DisplayName),
new XElement("PhoneNumber", c.FirstOrDefault().PhoneNumber.ToString()),
new XElement("Email", "abc#abc.com"));
doc.Root.Add(contactsElement);
doc.Save(file);
}
The first issue is in first line of code i.e. MapPath("~/XMLFile1.xml"); It gives me an error
The name 'MapPath' does not exist in the current context
The second issue is in doc.Save(file); It gives me an error
The best overloaded method match for 'System.Xml.Linq.XDocument.Save(System.IO.Stream)' has some invalid arguments
I have refer this question How to insert data into an existing xml file in asp.net?
I am learning XML. So, how can I solve this?
The reason why MapPath does not exist in the current context is because it is a method of HttpServerUtility class, and as far as I know, it is not supported on Windows Phone.
Try loading the XDocument like this:
XDocument xdocument = XDocument.Load("XMLFile1.xml");
EDIT: You were having an error saving the document. Here is an answer from a related thread:
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (Stream stream = storage.CreateFile("data.xml"))
{
doc.Save(stream);
}
}
Adding onto Kajzer's answer, here is another alternative that may be easier to grasp and use for saving an XDocument:
string path = "[some path]";
using (Stream stream = File.Create(path))
{
doc.Save(stream);
}
There is just one using statement, and you'll only need the System.IO class as it provides both the Stream and File classes for you to use - making this the most straightforward and easiest to understand solution.

Write out xmlwriter to file

I have an xmlwriter object used in a method. I'd like to dump this out to a file to read it. Is there a straightforward way to do this?
Thanks
Use this code
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Add a price element.
XmlElement newElem = doc.CreateElement("price");
newElem.InnerText = "10.95";
doc.DocumentElement.AppendChild(newElem);
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter(#"C:\data.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
As found on MSDN: http://msdn.microsoft.com/en-us/library/z2w98a50.aspx
One possibility is to set the XmlWriter to output to a text file:
using (var writer = XmlWriter.Create("dump.xml"))
{
...
}

Categories