在 C# 应用程序中存储数据的最佳方式是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19280555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to store data in c# application
提问by Biljana M.
I want to make Cookbook application for storing and reading (and updating) recipes, or anything else to practice OOP programming and thinking. But, I am not sure, what way of storing data, in this case, recipes, is the best in c# (Visual Studio Express). I want to optimize saving and loading data in program, but I have no experience. What is the best way? Is it through XML, SQL, or just plain TXT? Or some other way?
我想制作用于存储和阅读(和更新)食谱的 Cookbook 应用程序,或者其他任何东西来练习 OOP 编程和思考。但是,我不确定在 c# (Visual Studio Express) 中,哪种存储数据的方式(在这种情况下是配方)是最好的。我想优化在程序中保存和加载数据,但我没有经验。什么是最好的方法?是通过 XML、SQL 还是纯 TXT?还是其他方式?
采纳答案by Harrison
I would suggest using a localDB in SqlExpress.
我建议在 SqlExpress 中使用 localDB。
Microsoft? SQL Server? 2012 Express is a powerful and reliable free data management system that delivers a rich and reliable data store for lightweight Web Sites and desktop applications.
微软?SQL服务器?2012 Express 是一款功能强大且可靠的免费数据管理系统,可为轻量级网站和桌面应用程序提供丰富可靠的数据存储。
http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx
http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx
http://technet.microsoft.com/en-us/library/hh510202.aspx
http://technet.microsoft.com/en-us/library/hh510202.aspx
You could also look at this similar question.
你也可以看看这个类似的问题。
Here as an article on XML vs. DBwhich shows XML is losing ground.
这是一篇关于XML 与 DB的文章,其中显示 XML 正在失势。
回答by George Mavritsakis
Your best bet would be to use Sql Server Compact (http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/compact.aspx1).
您最好的选择是使用 Sql Server Compact ( http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/compact.aspx 1)。
That is because it comes embedded with your application and you don't need to install extra libraries on deployments etc. Also it is a good storage point for simple tabular data.
那是因为它嵌入在您的应用程序中,您不需要在部署等上安装额外的库。它也是简单表格数据的一个很好的存储点。
回答by BRAHIM Kamel
try to use SQLite it's lightweight portable database http://www.sqlite.org/
尝试使用 SQLite 它是轻量级的便携式数据库 http://www.sqlite.org/
回答by FredrikR
It depends a lot of how much data the application will hold and how you want to search for that data.
这在很大程度上取决于应用程序将保存多少数据以及您希望如何搜索这些数据。
For smaller amounts of data a plain text file containing XML och JSON will do. For larger amounts of data i recommend SQL server or a NOSQL-database (MongoDB or Raven).
对于少量数据,包含 XML 和 JSON 的纯文本文件就可以了。对于大量数据,我推荐 SQL 服务器或 NOSQL 数据库(MongoDB 或 Raven)。
回答by Trevor Elliott
If you haven't done it yet it would be best to start with XML file input/output before getting into anything too advanced.
如果您还没有这样做,最好先从 XML 文件输入/输出开始,然后再进入任何太高级的内容。
Normally you would read and write to files by using the following method to get the path:
通常,您将使用以下方法读取和写入文件以获取路径:
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
So if you want to store your data in a folder called "Cookbook" and a file called "recipes.xml" you could do the following:
因此,如果您想将数据存储在名为“Cookbook”的文件夹和名为“recipes.xml”的文件中,您可以执行以下操作:
string dataPath = Path.Combine(appDataPath, "Cookbook");
string recipesFileFullPath = Path.Combine(dataPath, "recipes.xml");
This gives you a path like C:\Users\John\AppData\Local\Cookbook\recipes.xml
or something similar which you can pass to file input and output functions.
这为您提供了一个类似C:\Users\John\AppData\Local\Cookbook\recipes.xml
或类似的路径,您可以将其传递给文件输入和输出函数。
Then you can get started with the System.IO
namespace classes like File
and FileStream
to learn how to properly open and read/write to files.
然后,您可以开始使用System.IO
命名空间类,如File
并FileStream
学习如何正确打开和读/写文件。
Then the next higher level step is to pass these file streams to something used to read and write XML to objects, such as Linq to XML (the XDocument
class) which is the preferred approach. Or the older XmlSerializer
.
然后下一个更高级别的步骤是将这些文件流传递给用于读取和写入 XML 到对象的东西,例如 Linq to XML(XDocument
类),这是首选方法。或者年纪大的XmlSerializer
。
Edit:
编辑:
Here's some sample code to create an object and save it to an XML file:
下面是一些用于创建对象并将其保存到 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);
}
You would just need to break this code out into a structure that works for you. For example, if you were making a Windows Forms application then the RecipeBook
would be a private member variable of your main form. In the constructor you could construct the recipesFileFullPath
string and store it as a private member variable too. On the Form.Loaded event you could check if the XML file already exists and if so load it. If not you would create a new RecipeBook
class that's empty. You would also probably only serialize and save when the user clicks a save button or when the Form.Closing event is raised.
您只需要将此代码分解为适合您的结构即可。例如,如果您正在制作 Windows 窗体应用程序,那么RecipeBook
将是主窗体的私有成员变量。在构造函数中,您可以构造recipesFileFullPath
字符串并将其存储为私有成员变量。在 Form.Loaded 事件中,您可以检查 XML 文件是否已经存在,如果存在则加载它。如果不是,您将创建一个RecipeBook
空的新类。您也可能只在用户单击保存按钮或引发 Form.Closing 事件时序列化和保存。
EDIT:
编辑:
To deserialize and read from a file you can do the following:
要反序列化和读取文件,您可以执行以下操作:
var serializer = new XmlSerializer(typeof(RecipeBook));
using (var fs = new FileStream(recipesFileFullPath))
{
RecipeBook book = (RecipeBook)serializer.Deserialize(fs);
}
回答by Captain Skyhawk
This depends on a lot of things, mostly how many recipes you plan on having and if you want to be able to search, sort, or style the recipes.
这取决于很多事情,主要是您计划拥有多少食谱,以及您是否希望能够搜索、排序或设置食谱样式。
Text files are the simplest way. You could add some simple search and ordering functionality.
文本文件是最简单的方法。您可以添加一些简单的搜索和排序功能。
If it's in this hundreds, you could get by with using xml and a serializer. It would allow you to later style the recipes and it gives the data some structure. If your recipes enter the thousands, this way may become a nightmare.
如果有数百个,您可以使用 xml 和序列化程序。它将允许您稍后为食谱设置样式,并为数据提供一些结构。如果您的食谱进入数千种,这种方式可能会成为一场噩梦。
The best way would be a database. Sql Server Compact is a free option that links up nicely with c# through something like Entity Framework. This option will take the longest by far if you're not already familiar with databases or ado.net or entity framework.
最好的方法是数据库。Sql Server Compact 是一个免费选项,它通过诸如实体框架之类的东西与 c# 很好地链接。如果您还不熟悉数据库、ado.net 或实体框架,则此选项将花费最长的时间。