如何使用XML文件作为资源在Windows窗体应用程序中进行读写

时间:2015-05-24 23:01:14

标签: c# xml resources linq-to-xml

我正在编写一个使用一些资源的小型Windows窗体应用程序(在C#中)。其中一个资源是XML文件。

应该在初始化第一个Form之前读取此XML文件。 XML文件的内容用于创建应用程序使用的对象。

通常我会在Visual Studio中将此XML文件添加为资源。

  

项目属性>资源>文件>添加现有文件

然后在应用程序中,我可以使用:XDocument.Parse(Resources.NameOfXMLResource)

读取XML文件的内容

在这个应用程序中,我希望能够添加或更新对象,这也应该更新XML文件中存储的信息。我知道我无法将更新的XML文件保存到Resources.NameOfXMLResource,因为它实际上是一个包含XML文件所有内容的字符串。

我在C#项目中看到很多关于XML作为资源的帖子,但大多数帖子只是关于从资源中读取而不是写入它。

所以我的问题是:如何设置XML文件..

  • 作为我可以读/写的资源;

    当我运行setup.msi时,
  • 将它存储在安装文件夹中的某个位置,该setup.msi会在所需位置安装.exe(应用程序)。 (使用这种方法,我需要具有读/写访问权限,并且能够在不先安装的情况下调试项目)

我目前读取/写入XML文件的代码:

this.file = Resources.XMLItemList;

public List<ItemModel> GetStoredItems()
{
  return (from item in XDocument.Load(this.file).Descendants("Item")
          select new ItemModel
          {
            Name = item.Attribute("Name").Value,
            ID = item.Element("ID").Value,
            Description = item.Element("Description").Value,
            Size = Convert.ToInt32(item.Element("Size").Value),
            Path = item.Element("Path").Value
          }).ToList();
}

public string AddItem(ItemModel item)
{
  try
  {
    var xdoc = XDocument.Load(this.file);
    xdoc.Element("Items").Add(new XElement("Item",
                              new XAttribute("Name", item.Name),
                              new XElement("ID", item.ID),
                              new XElement("Description", item.Description),
                              new XElement("Size", item.Size),
                              new XElement("Path", item.Path)));
    xdoc.Save(this.file);
    return null;
  }
  catch (Exception ex)
  {
    return string.Format(Resources.ErrCanNotAddItemToXML, ex);
  }
}

0 个答案:

没有答案