如果您还没有这样做,最好先从 XML 文件输入/输出开始,然后再进行任何太高级的操作。
通常你会通过使用以下方法来读取和写入文件来获取路径:
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
因此,如果您想将数据存储在名为“Cookbook”的文件夹和名为“recipes.xml”的文件中,您可以执行以下操作:
string dataPath = Path.Combine(appDataPath, "Cookbook");
string recipesFileFullPath = Path.Combine(dataPath, "recipes.xml");
这会为您提供类似C:\Users\John\AppData\Local\Cookbook\recipes.xml 或类似的路径,您可以将其传递给文件输入和输出函数。
然后您可以开始使用System.IO 命名空间类,例如File 和FileStream,以了解如何正确打开和读取/写入文件。
然后下一个更高级别的步骤是将这些文件流传递给用于读取和写入 XML 到对象的东西,例如 Linq to XML(XDocument 类),这是首选方法。或较旧的XmlSerializer。
编辑:
以下是一些创建对象并将其保存到 XML 文件的示例代码:
public class RecipeBook
{
public List<Recipe> Recipes { get; set; }
public RecipeBook()
{
Recipes = new List<Recipe>();
}
}
public class Recipe
{
public DateTime LastModified { get; set; }
public DateTime Created { get; set; }
public string Instructions { get; set; }
}
public void SomeFunction()
{
RecipeBook recipeBook = new RecipeBook();
var myRecipe = new Recipe()
{
Created = DateTime.Now,
LastModified = DateTime.Now,
Instructions = "This is how you make a cake."
};
recipeBook.Recipes.Add(myRecipe);
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
var serializer = new XmlSerializer(typeof(RecipeBook));
serializer.Serialize(writer, recipeBook);
}
doc.Save(recipesFileFullPath);
}
您只需要将这段代码分解成适合您的结构。例如,如果您正在制作 Windows 窗体应用程序,那么 RecipeBook 将是主窗体的私有成员变量。在构造函数中,您可以构造recipesFileFullPath 字符串并将其存储为私有成员变量。在 Form.Loaded 事件中,您可以检查 XML 文件是否已经存在,如果存在则加载它。如果不是,您将创建一个新的 RecipeBook 类,它是空的。您也可能只在用户单击保存按钮或引发 Form.Closing 事件时进行序列化和保存。
编辑:
要反序列化并从文件中读取,您可以执行以下操作:
var serializer = new XmlSerializer(typeof(RecipeBook));
using (var fs = new FileStream(recipesFileFullPath))
{
RecipeBook book = (RecipeBook)serializer.Deserialize(fs);
}