Please suggest me a method to save an XML file to the current installation directory of the application created using C#.
4 Answers
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.
2 Comments
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");
1 Comment
/myXML.xml instead of \myXML.xml, but it sure looks wrong. I'd go with Henk's Path.Combine().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.
XDocument,XmlDocument, ...?