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

4

2 回答 2

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

于 2013-02-25T17:43:16.100 回答
-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 文件。

于 2013-02-26T10:14:16.317 回答