[好,所以我试图构建一个程序,使我可以制作Recipe数据库。我要保存的数据为;
class RecipeDataBase
{
int RecipeID;
string RecipeNames;
string[,] Ingredients = new string[30, 30];
string[] Steps = new string[30];
}
我首先要让程序执行的操作,它有一个create new database选项,它将在其中创建一个带有配方数据库名称(例如DinnerRecipes.rdb)的空保存文件。然后,我有另一种表单,旨在允许用户将食谱添加到他们选择的任何数据库中,最后我有另一种表单,允许用户编辑数据库中的食谱,并列出他们在该数据库中的所有当前食谱名称选择。
想法是,我有一个程序,可以为正在研究的另一个程序创建几乎数字的食谱。而我所知道的代码中几乎有85%,其余的我都将其保存为我自己的这个savefile部分。
目前,我只有;
//Setting up and restricting the save system
SaveFileDialog CRDB = new SaveFileDialog();
CRDB.InitialDirectory = @"./";
CRDB.RestoreDirectory = true;
CRDB.FileName = "*.rdb";
CRDB.Filter = "Recipe Database |*.rdb";
//running the save display and if they click ok creating a blank datebase.
if (CRDB.ShowDialog() == DialogResult.OK)
{
//This is to prep the database template for saving and creating the database file.
RecipeDataBase recipes = new RecipeDataBase();
Stream fileStream = CRDB.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
sw.Write(recipes);
sw.Close();
fileStream.Close();
}
好吧,我想我可能会使事情变得比实际更复杂。但是,这是我要保存的数据的示例
RecipeID = 1;
RecipeNames = "Homemade Pasta Sauce";
Ingredients = ["Tomato", "Basil", "Onions", "Garlic", ect...]["4", "6 leaves or a tablespoon of ground", "3 Medium Sized", "8 clove(minced)", ect..];
Steps = ["Peel and seed the tomatoes and set aside.", "Chop the onion, mince the garlic, and grate half of the carrot.", "Pour the olive oil into a large stockpot over medium heat.", ect];
最近三天,我一直在寻找所需的答案,我不知道我是问错了还是只是没有将找到的答案与项目联系起来。请帮助我Stackoverflow Kenobi您可能只希望。
您应该将数据序列化为可以保存的格式,通常是JSON或XML字符串或二进制格式,例如protobuff或MessagePack。有关序列化的更多详细信息,可以在这里找到:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/
和
https://docs.microsoft.com/en-us/dotnet/standard/serialization/basic-serialization
您可能必须更改类,例如添加默认构造函数或[Serializable]
属性。
一些序列化示例(来自链接):
二进制:
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
JSON:
string jsonString = JsonSerializer.Serialize(weatherForecast);
File.WriteAllText(fileName, jsonString);