简体   繁体   中英

Create an XML file using C#

请向我建议一种将XML文件保存到使用C#创建的应用程序的当前安装目录中的方法。

  1. Create an XML file: The easiest way is to create and populate an XmlDocument or XDocument object.

  2. 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.

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

StringBuilders和HttpUtility.HtmlEncode通常可以很好地工作。

And, after you've tried everything and are still scratching your head, wondering why it isn't working...

  1. 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.
  2. 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
  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM