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

Din*_*aud 3 c# xml asp.net 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);
}
Run Code Online (Sandbox Code Playgroud)

我想将xml文件保存在我在项目中创建的文件夹中.然后我将使用在我的文件夹中创建的xml文件并从中读取和写入.知道怎么做吗?

Zai*_*mir 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");
Run Code Online (Sandbox Code Playgroud)

虽然您应该注意,例如,如果您的应用程序安装在C:\ Program Files中,您将需要某种提升权限才能在此处写入,具体取决于您的应用程序部署在计算机上的安全设置.最好总是在某个其他位置(例如(应用程序数据))有一个工作目录.