如果您还没有这样做,那么最好先从 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
and FileStream
了解如何正确打开和读/写文件。
然后,下一个更高级别的步骤是将这些文件流传递给用于将 XML 读写到对象的东西,例如 Linq to XML(XDocument
class)这是首选方法。或者年龄较大的XmlSerializer
.
Edit:
以下是创建对象并将其保存到 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 事件时序列化和保存。
EDIT:
要反序列化并读取文件,您可以执行以下操作:
var serializer = new XmlSerializer(typeof(RecipeBook));
using (var fs = new FileStream(recipesFileFullPath))
{
RecipeBook book = (RecipeBook)serializer.Deserialize(fs);
}