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

时间:2013-02-25 17:16:08

标签: c# asp.net xml entity-framework

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文件并从中读取和写入。知道怎么做吗?

2 个答案:

答案 0 :(得分:5)

使用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中,您需要某种提升权限才能在那里写入,具体取决于您的应用已部署的计算机的安全设置上。最好总是在其他位置(例如(应用程序数据))有一个工作目录。

答案 1 :(得分:-1)

使用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文件中读取和写入。