将XML文件保存在项目文件夹中

本文关键字:项目文件 文件夹 项目 存在 XML 文件 保存 | 更新日期: 2023-09-27 18:00:55

try
{
    XElement contactsFromFile = XElement.Load("App_Data/EmployeeFinList.xml");
    var xEle = new XElement("Employees",
        from emp in ListFromBasicPay
        select new XElement("Employee",
            new XAttribute("EmpID", emp.employee_personal_id),
            new XElement("GrandTotal", emp.grandTotal),
            new XElement("Housing", emp.housing),
            new XElement("BasePay", emp.base_pay),
            new XElement("XchangeRate", emp.Exchange_rate)));
    xEle.Save("..''changesetDB.xml");
    Debug.WriteLine("Converted to XML");
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
}

我想把xml文件保存在我在项目中创建的文件夹中。然后,我将使用在我的文件夹中创建的xml文件,并从中进行读写。知道怎么做吗?

将XML文件保存在项目文件夹中

使用System.Reflection.Assembly.GetExecutingAssembly().Location要获得程序集的完整路径,请将其与System.IO.Path.GetDirectoryName()结合使用。

这就像:

String path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
xEle.Save(path + @"'myfilename.xml");

尽管你应该注意,例如,如果你的应用程序安装在C:''Program Files中,你需要某种提升权限才能在那里写入,这取决于你的应用软件部署在的计算机的安全设置。最好总是在其他位置有一个工作目录,例如(应用程序数据(。。

使用Red Serpent的答案获取项目的文件夹:

  String path = System.IO.Path.GetDirectoryName
  (System.Reflection.Assembly.GetExecutingAssembly().Location);

然后使用:

   string mySavePath = Path.Combine(path, myFolder);
   string myXMLPath = Path.Combine(SavePath,"changesetDB.xml");

然后,您可以使用myXMLPath从刚刚创建的XML文件中进行读写操作。