1.写一个保存xml文件到本地文件的工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace TestDemo1
{
internal class SaveXmlUtil
{
public static String SaveXmlToLocalhost(XmlDocument obj,String filePath,String fileName)
{
try
{
if(obj == null)
{
return String.Empty;
}
else
{
// 文件路径
filePath = filePath + "\\" + System.DateTime.Now.ToString("yyyy-MM-dd");
// 如果没有目录则创建
if (Directory.Exists(filePath) == false)
{
Directory.CreateDirectory(filePath);
}
try
{
String savePath = Path.Combine(filePath, fileName);
obj.Save(savePath);
}
catch (Exception ex)
{
return String.Empty;
}
return obj.OuterXml.ToString();
}
}catch (Exception ex)
{
return String.Empty;
}
}
}
}
2.外部调用工具类
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
String filePath = "D:\\Hao\\xml";
String fileName = "NewFile"+".xml";
String rsData = SaveXmlUtil.SaveXmlToLocalhost(xmlDoc, filePath, fileName);
}