Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store data from a C# application

Tags:

c#

.net

I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.

My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application?


Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;). I'm used to building web applications and for those, text files are generally frowned upon.

So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?

like image 712
Justin Bennett Avatar asked Aug 21 '08 14:08

Justin Bennett


People also ask

Why do we need to store data in file in C?

Why files are needed? When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates. If you have to enter a large number of data, it will take a lot of time to enter them all.


3 Answers

Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure.


using (FileStream fs = new FileStream(....))
{
    // Read in stats
    XmlSerializer xs = new XmlSerializer(typeof(GameStats));
    GameStats stats = (GameStats)xs.Deserialize(fs);

    // Manipulate stats here ...

    // Write out game stats
    XmlSerializer xs = new XmlSerializer(typeof(GameStats));
    xs.Serialize(fs, stats);

    fs.Close();
}
like image 55
Brian Ensink Avatar answered Oct 14 '22 01:10

Brian Ensink


A database would probably be overkill for something like this - start with storing your information in an XML doc (or series of XML docs, if there's a lot of data). You get all that nifty XCopy deployment stuff, you can still use LINQ, and it would be a smooth transition to a database if you decided later you really needed performant relational query logic.

like image 27
Greg Hurlman Avatar answered Oct 14 '22 01:10

Greg Hurlman


A database may be overkill - have you thought about just storing the scores in a file?

If you decide to go with a database, you might consider SQLite, which you can distribute just like a file. There's an open source .NET provider - System.Data.SQLite - that includes everything you need to get started.

Accessing and reading from a database in .NET is quite easy - take a look at this question for sample code.

like image 33
palmsey Avatar answered Oct 14 '22 01:10

palmsey