Please suggest me a method to save an XML file to the current installation directory of the application created using C#.
+8
A:
Create an XML file: The easiest way is to create and populate an XmlDocument or XDocument object.
Save to the install directory: use
string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath); string file = System.IO.Path.Combine(pathm, "myfile.xml");
But you do know that the application's folder isn't the best place to store a file, right?
Edit:
Some comments mention Isolated Storage, but that is overkill. The best way to store data is to use the appropriate DataPath. That is different under various versions of Windows, but this always works:
string path =
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
There are a few other values in the Environment.SpecialFolder
enum, take a look.
Henk Holterman
2009-09-13 09:53:08
+1 for SpecialFolder.ApplicationData. Hope you don't mind my editing your answer, but I hate the horizontal scrollbar for code samples.
MusiGenesis
2009-09-13 15:36:50
Yep +1 for ApplicationData. In truth I was probably thinking of that when I suggested Isolated Storage.
Matt Hamilton
2009-09-15 07:15:19
+7
A:
Using XDocument and LINQ:
XDocument myXml = new XDocument(new XElement("Node 1", new XElement("Node 2")));
myXml.Save(Directory.GetCurrentDirectory() + "/myXML.xml");
or
XDocument myXml = new XDocument(new XElement("Node 1", new XElement("Node 2")));
myXml.Save(Path.GetDirectoryName(Application.ExecutablePath) + "/myXML.xml");
Henrik P. Hessel
2009-09-13 09:57:41
I know the code works with `/myXML.xml` instead of `\myXML.xml`, but it sure *looks* wrong. I'd go with Henk's Path.Combine().
MusiGenesis
2009-09-13 12:49:42
A:
StringBuilders and HttpUtility.HtmlEncode usually work quite well.
erikkallen
2009-09-13 13:22:17
A:
And, after you've tried everything and are still scratching your head, wondering why it isn't working...
- Make sure the folder you want to save to ALLOWS Writing by the account the Web service is running under or the user (depending on how you have security configured); this should be done at the NTFS level. Previous suggestions said that it would be bad to write in the application folder. No, it wouldn't be bad, it would be incredibly stupid to write there, not just bad. So, pick somewhere else to save the data. Ideally on another physical volume, or better still: post the XML file to another application on another server who's only lot in life is saving this data.
- Assuming you know how to create an XML document in C# (strings ain't it - use the proper methods for building an XmlDocument - like by using elements and nodes and attributes), you can use the .Save method
- Why not use strings??? Because you'll spend more time debugging "well-formed XML" errors than you will solving your actual problem. People are lousy at making well-formed XML. Machines are pretty good at it.
inked
2009-10-28 19:49:05