我必须在app.config
的帮助下保存文件<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appsetting>
<add key ="filename" value ="abc.xml"></add>
<add key="filepath" value ="C:\\Users\\saket.parasar.jha"></add>
</appsetting>
</configuration>
我将xml文件保存到指定路径的代码 - :
XmlDocument doc = new XmlDocument();
//XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
//doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
{
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "1";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
AddUpdateAppSettings("filename", "abc.xml");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
我必须将该xml文件写入C:\ Users \ saket.parasar.jha“使用c#...请帮助我,我是这个主题的新手。我尝试了很多但是却无法保存文件。
答案 0 :(得分:1)
首先,您永远不能以编程方式修改app.config文件。在您的应用运行时,永远不会更改内部设置。这些设置类似于“预启动”。如果您需要用户可修改的任何设置,请使用设置文件(添加&gt;新项目&gt;常规&gt;设置文件),扩展名为* .settings的设置。另外,我没有看到你试图从你的配置文件中获取你的设置,你只是将它们保存在那里(但你不能这样做,原因如上)。 正确获得路径后,可以将文件保存在那里。
P.S。:不允许修改App.config,因为它与应用程序位于同一目录中(修改后的名称如MyApplication.exe.config);当您的应用程序安装在目标系统上时,目标目录很可能是“程序文件”。如您所知,任何修改配置的尝试都需要提升权限(如管理员)。这意味着您的应用非常不友好。
答案 1 :(得分:0)
为什么不保存您的XmlDocument?
之类的东西doc.Save("C:\\Users\\saket.parasar.jha\\abc.xml");