如何在 C# 的配置位置编写和保存 XMl 文件

本文关键字:保存 XMl 文件 位置 配置 | 更新日期: 2023-09-27 18:30:32

我有以下代码来编写XML。但它在成功运行后存储在Bin文件夹中。问题是:I希望将其存储在某个指定的可配置网络位置,而不是 Bin 文件夹中。知道吗?

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);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
// Save the document to a file and auto-indent the output.
XmlWriter writer = XmlWriter.Create("data.xml", settings);
doc.Save(writer);

谢谢

如何在 C# 的配置位置编写和保存 XMl 文件

您只需在那里传递路径而不是数据.xml

XmlWriter.Create("C:'MyFolder'data.xml");

由于您希望它是可配置的,因此我建议您使用 App.Config 和 ConfigurationManager 来设置所需的路径。

基本上它看起来像这样

(在您的代码中:)

string path = ConfigurationManager.AppSettings["SaveFilePath"];

(应用配置:)

<configuration>
  <appSettings>
    <add key="SaveFilePath" value="C:'BlaBla'data.xml"/>
      </appSettings>
</configuration>