-2

Is there a way to 'save' userdata in textfiles (.txt) and re-use them? I'm programming in C# Visual Studio 2013 (WFA) Databases/XML files are not allowed!

For example, I program a quiz with several questions. When I start the quiz and give some correct and false answers, I need to be able to save my answers, see my correct/false answers and I have to be able to retry my false answers.

Zong
  • 6,160
  • 5
  • 32
  • 46
  • 1
    Yes, it is certainly possible. Have you tried anything? Learned about working with files? – crashmstr May 09 '14 at 13:46
  • Typing in google `c# text files` is surely much more faster way to get answers, than typing this question here. – Sinatr May 09 '14 at 13:48
  • What Sinatr said is true, although i am inclined to believe that you did not know what to type, and the correct thing, based on your question, is called a streamreader and stream writer, there are tons of tutorials and examples on the web, but please do comment if you find yourself having difficulty along the way. i will assist you, good luck! – Jonny May 09 '14 at 13:52

2 Answers2

1

The short answer is yes. The long answer isn't too bad either. Let's say we structure a set of classes like this:

public class Quiz
{
    public List<Question> Questions { get; set; }

    public Quiz() { Questions = new List<Question>(); }
}

public class Question
{
    public string Question { get; set; }

    public bool Answer { get; set; }
}

Now let's say the UI builds a nice collection of questions for a quiz and over time sets the answer to true or false, yes or no have you, and so at the end we need to save it:

File.WriteAllText(path, JsonConvert.SerializeObject(quiz));

This will save the entire quiz and questions in a JSON format to a file path.

Now we need to reload; this is why I used JSON:

var quiz = JsonConvert.DeserializeObject<Quiz>(File.ReadAllText(path));

After updates have been made to the object (i.e. answers changed) you can run this again:

File.WriteAllText(path, JsonConvert.SerializeObject(quiz));

NOTE: clearly (or it should be clear) each quiz will need its own file.

NOTE: this will also require that you get the Json.NET NuGet package, which can be installed with the NuGet Visual Studio Extension.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
1

There are many many examples of how to do this online and im sure plenty on stack overflow as well.

To Read from a .txt file check this out

Reading textFile and saving the info into an array C#

To Write to a text file, check this out

Saving from List<T> to txt

Community
  • 1
  • 1
Jwit
  • 156
  • 6