0

I need guidance, someone to point me in the right direction. As the tittle says, I need to save information to a file: Date, string, integer and an array of integers. And I also need to be able to access that information later, when an user wants to review it. Optional: File is plain text and I can directly check it and it is understandable. Bonus points if chosen method can be "easily" converted to working with a database in the future instead of individual files.

I'm pretty new to C# and what I've found so far is that I should turn the array into a string with separators.

So, what'd you guys suggest?

  • Put all the information you want to persist into a serializable class, and [use serialization to write it to an XML file](https://msdn.microsoft.com/en-us/library/4abbf6k0(v=vs.110).aspx/). – Matthew Watson Jun 01 '17 at 08:58
  • The bonus point part is shouting for you to use CSV in my opinion. – Sash Sinha Jun 01 '17 at 08:59

4 Answers4

1
// JSON.Net
string json = JsonConvert.SerializeObject(objOrArray);
File.WriteAllText(path, json);
// (note: can also use File.Create etc if don't need the string in memory)

or...

using(var file = File.Create(path)) { // protobuf-net
    Serializer.Serialize(file, objOrArray);
}

The first is readable; the second will be smaller. Both will cope fine with "Date, string, integer and an array of integers", or an array of such objects. Protobuf-net would require adding some attributes to help it, but really simple.

As for working with a database as columns... the array of integers is the glitch there, because most databases don't support "array of integers" as a column type. I'd say "separation of concerns" - have a separate model for DB persistence. If you are using the database purely to store documents, then: pretty much every DB will support CLOB and BLOB data, so either is usable. Many databases now have inbuilt JSON support (helper methods, etc), which might make JSON as a CLOB more tempting.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

I would probably serialize this to json and save it somewhere. Json.Net is a very popular way.

The advantage of this is also creating a class that can be later used to work with an Object-Relational Mapper.

    var userInfo = new UserInfoModel();


    // write the data (overwrites)
    using (var stream = new StreamWriter(@"path/to/your/file.json", append: false))
    {
        stream.Write(JsonConvert.SerializeObject(userInfo));   
    }

    //read the data
    using (var stream = new StreamReader(@"path/to/your/file.json"))
    {
        userInfo = JsonConvert.DeserializeObject<UserInfoModel>(stream.ReadToEnd());
    }

    public class UserInfoModel
    {
         public DateTime Date { get; set; }
        // etc.
    }
robjam
  • 969
  • 1
  • 11
  • 24
0

for the Plaintext File you're right. Use 1 Line for each Entry: Date string Integer Array of Integer

If you read the File in your code you can easily seperate them by reading line to line.

Make a string with a specific Seperator out of the Array: [1,2,3] -> "1,2,3" When you read the line you can Split the String by "," and gets a Array of Strings. Parse each Entry to int into an Array of Int with the same length.

How to read and write the File get a look at Easiest way to read from and write to files

If you really wants the switch to a database at a point, try a JSON Format for your File. It is easy to handle and there are some good Plugins to work with.

Mfg Henne

-1

The way I got started with C# is via the game Space Engineers from the Steam Platform, the Mods need to save a file Locally (%AppData%\Local\Temp\SpaceEngineers\ or %AppData%\Roaming\SpaceEngineers\Storage\) for various settings, and their logging is similar to what @H. Sandberg mentioned (line by line, perhaps a separator to parse with later), the upside to this is that it's easy to retrieve, easy to append, easy to overwrite, and I'm pretty sure it's even possible to retrieve File Size, which when combined with File Deletion and File Creation can prevent runaway File Sizes as this allows you to set an Upper Limit to check against, allowing you to run it on a Server with minimal impact (probably best to include a minimum Date filter {make sure X is at least Y days old before deleting it for being over Z Bytes} to prevent Debugging Data Loss {"Why was it over that limit?"})

As far as the actual Code behind the idea, I'm approximately at the same Skill Level as the OP, which is to say; Rookie, but I would advise looking at the Coding in the Space Engineers Mods for some Samples (plus it's not half bad for a Beta Game), as they are almost all written in C#. Also, the Programmable Blocks compile in C# as well, so you'll be able to use that to both assist in learning C# and reinforce and utilize what you already know (although certain C# commands aren't allowed for security reasons, utilizing the Mod API you'll have more flexibility to do things such as Creating/Maintaining Log Files, Retrieving/Modifying Object Properties, etc.), You are even capable of printing Text to various in Game Text Monitors.

I apologise if my Syntax needs some work, and I'm sorry I am not currently capable of just whipping up some Code to solve your issue, but I do know

using System;
Console.WriteLine("Hello World");

so at least it's not a total loss, but my example Code likely won't compile, since it's likely missing things like: an Output Location, perhaps an API reference or two, and probably a few other settings. Like I said, I'm New, but that is a valid C# Command, I know I got that part correct.

Edit: here's a better attempt:

using System;
class Test
{
    static void Main()
    {
        string a = "Hello Hal, ";
        string b = "Please open the Airlock Doors.";
        string c = "I'm sorry Dave, "
        string d = "I'm afraid I can't do that."
        Console.WriteLine(a + b);
        Console.WriteLine(c + d);
        Console.Read();
    }
}

This:

"Hello Hal, Please open the Airlock Doors."
"I'm sorry Dave, I'm afraid I can't do that."

Should be the result. (the "Quotation Marks" shouldn't appear in the readout {the last Code Block}, that's simply to improve readability)

Blue64
  • 1
  • 3
  • I'm a (was, more accurately) Space Engineers player, the option to code interested me but never got time to dive into it. I'm playing Starbound now haha. – LightningLion Jun 01 '17 at 21:36
  • The right YouTube channel can make all the difference. Even without Coding, there's plenty of Mods out there that allows you to simply rename a few Blocks (which you'd likely have done anyways) and you're set up. I use one for Inventory Management, on top of that there's plenty of already created Scripts to browse in the Steam Workshop for a wide variety of tasks. Just remember to "Check Code" in the Programmable Block before you Save and Run it. – Blue64 Jun 01 '17 at 23:43