C#. Writing settings to XML file - c#

I have some names of files. I am creating a XML file to store them. When application runs second time it should recognize those file names. Here is my code:
XmlWriter writer = XmlWriter.Create("settings.xml");
writer.WriteStartElement("DialogCreater");
writer.WriteElementString("conditionsFile", conditionsFile);
writer.WriteEndElement();
writer.Close();
But when I use those file names like this:
string[] lines = File.ReadAllLines(charactersFile);
It gives me an error.
System.NotSupportedException
Here how I read them from XML file:
XmlDocument doc = new XmlDocument();
doc.Load("settings.xml");
XmlNodeList node = doc.GetElementsByTagName("files");
foreach (XmlNode n in node[0].ChildNodes)
{
if (n.Name == "conditionsFile") conditionsFile = n.InnerText;
}

NotSupportedException
path is in an invalid format according to msdn documentation. you can fix it by checking path exist or not before reading from itMore info
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
//file exist
}

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

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);
}

How to read XML document and display the output as string in c#

consider my source file looks like this.
<Content xmlns="uuid:4522eb85-0a47-45f9-8e2b-1x82c78xx920">
<first>Hello World.This is Fisrt field</first>
<second>Hello World.This is second field</second>
</Content>
I want to write a code, which read this xml document from a location and display it as string.
say name of the xml file is helloworld.xml.
Location: D:\abcd\cdef\all\helloworld.xml.
I have tried the following, but i was unable to do it.
XmlDocument contentxml = new XmlDocument();
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write("<BR>" + contentxml.ToString());
Response.write is displaying nothing. Correct me if i missed any thing. Its not creating any component and error is coming.
I have also tried this,
XmlDocument contentxml = new XmlDocument();
try
{
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
}
catch (XmlException exp)
{
Console.WriteLine(exp.Message);
}
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
contentxml.WriteTo(xw);
Response.Write("<BR>" + sw.ToString());
But i did not find the any output.
I want to read a XML file from a location and display it as it is as string.
Can anyone help on this.
Thank you,
Muzimil.
You need the OuterXml property:
Response.Write("<BR>" + contentxml.OuterXml);
Also you are loading a file not xml so use
contentxml.Load(#"D:\abcd\cdef\all\helloworld.xml");
instead of
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Do you really have to deserialize the XML at all? Why not just read it as a text file? Something like..
String text = File.ReadAllText(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write(text);
With appropriate error handling obviously..
I would try using the XDocument class:
//load the document from file
var doc = XDocument.Load("..."); //== path to the file
//write the xml to the screen
Response.Write(doc.ToString());
If you want to use an XmlDocument instead, you would want to use Load instead LoadXml.
If you want to simply write a file to the output, you can do Response.WriteFile.
try this
XmlTextReader reader = new XmlTextReader (#"D:\abcd\cdef\all\helloworld.xml");
while (reader.Read())
{
Console.WriteLine(reader.Name);
}
Console.ReadLine();
String text = File.ReadAllText(Server.MapPath("~/App_Data/sample.xml"));
txtData.Text = text;

C# and XML - Read XML files from user-specified location

Read sequentially through the XML files (e.g. C:\Application\XML) and get the xml for all the files.
You can read XML files as shown below:
List<string> files = Directory.GetFiles("c:\\MyDir", "*.xml").ToList();
foreach(string fileLocation in files)
{
XmlDocument obj = new XmlDocument();
obj.Load(filelocation);
//Your code to place the xml in a queue.
}
What you need to do is implement a producer-consumer model. Have a look here: http://www.albahari.com/threading/part4.aspx and scroll down to the "Producer/Consumer Queue" part.
For some classic C# XML API read here: http://msdn.microsoft.com/en-us/magazine/cc302158.aspx
foreach (var file in Directory.EnumerateFiles(path, "*.xml"))
{
var xdoc = XDocument.Load(file);
...
}

Trying to write to an existing XML file for C#

Thank you very much in advance
This is the original XML File
<my:Incident>
<my:Category>This is for Category</my:Category>
<my:Status>`Status is Close`</my:Status>
<my:Description>`This is the description part</my:Description>
</my:Incident>
and I would like to add other fields under my:Incident
This is an example of it:
<my:Incident>
<my:Category>This is for Category</my:Category>
<my:Status>`Status is Close`</my:Status>
<my:SummaryDescription>This is the summary</my:SummaryDescription>
<my:Description>`This is the description part</my:Description>
</my:Incident>
I tried to implemented but I got this error message:
The ':' character, hexadecimal value 0x3A, cannot be included in a name.
public void writerXMLTest(string fileName)
{
if (!File.Exists(fileName))
{
XmlTextWriter writer = new XmlTextWriter(fileName, null);
writer.WriteStartElement("my:Incident");
writer.WriteEndElement();
writer.Close();
}
XDocument doc = XDocument.Load(fileName);
XElement demoNode = new XElement("my:Incident");
demoNode.Add(new XElement("my:SummaryDescription", "Test Test"));
Console.WriteLine("I write it!!!!!");
}
I would appreciate if anyone can guide me where I did wrong in my code.
I modified the code a little. But now I'm not able to write it to the existing XML File
This is my code:
public void writerXMLTest(string fileName)
{
if (!File.Exists(fileName))
{
XmlTextWriter writer = new XmlTextWriter(fileName, null);
writer.WriteStartElement("Incident", "my");
writer.WriteEndElement();
writer.Close();
}
XDocument doc = XDocument.Load(fileName);
XElement demoNode = new XElement("SummaryDescription", "Test Test");
Console.WriteLine("I write it!!!!!");
}
This is wrong:
writer.WriteStartElement("my:Incident");
This is right:
writer.WriteStartElement("Incident", "blablablaSpace:my");
Edit:
writer.WriteStartElement("Incident", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2005-09-22T20:42:56:my");
There are several problems here. First your "original XML" is not valid because you have not defined the "my" namespace. Either you have not shown us the entire XML file, or you are hand-coding invalid XML. Don't do that.
I'm not able to write it to the existing XML File.
What does "I'm not able" mean? It throws an exception? What is the exception? Or do you mean your file is unchanged after running your code? That is unsurprising because your code doesn't actually do anything.
XDocument doc = XDocument.Load(fileName);
This loads your XML file from disk... and then does nothing with it. It doesn't change the file.
XElement demoNode = new XElement("SummaryDescription", "Test Test");
This creates a new XML element, totally unrelated to doc, the original file, or to anything else... and then throws it away without doing anything with it. You have not added it anywhere or saved anything to a file.
and I would like to add other fields under my:Incident
If you want to add demoNode to the file, you first must find the Incident node:
XElement e = doc.Descendants(XName.Get("Incident", nameSpace)).FirstOrDefault<XElement>();
Add your new element to it:
if (e != null)
{
e.Add( new XElement(XName.Get("SummaryDescription", nameSpace), "Test Test") );
}
Then save the changed document
doc.Save(fileName);
Your "my:" prefix is a namespace. You must use TagName = "Incident", Namespace="my".
Microsoft provides documentation on using XmlTextWriter with namespaces
http://msdn.microsoft.com/en-us/library/cfche0ka(v=vs.80).aspx

Categories