C# Coping array using a .txt

Viewed 72

Ok... i'm a total novice in the big world of programming.
Said that... i'm having problem with saving\loading one array.

For now i have altready found a way to save a .txt file with the content of the ArrayA.

The result would be a string like this "0,1,2,3,4"

But i can't find a way to use that .txt file for setting the ArrayB using that file. i'm totally sure i'm missing something dumb.

However, if someone else know an alternative method i'm very open try to other ways(as long as i can understand them).

EDIT1:

This is the code i have used for creating the savefile.

{
FileUtil.DeleteFileOrDirectory(Application.streamingAssetsPath + "/Ordini/" +
 "Ordine" + ".txt");

string txtDocumentname = Application.streamingAssetsPath + "/Ordini/" + 
"Ordine" + ".txt";

        for (int i = 0; i < 500; i++)
        {
            OrdineArray += ArrayMenù.Array[i] + " ;";
        }


        if (!File.Exists(txtDocumentname))
        {

            File.WriteAllText(txtDocumentname, OrdineArray);
        }

 } 







2 Answers

Let's take a step back. There are lots of ways to persist data (of any sort) to a file.

One common and idiomatic approach is to serialize it. Once again there are near endless ways to serialize data, however json is a great modern serialization solution.

Advantages

  1. It's easy to read
  2. It's easy to do
  3. There is a wealth of information on the libraries.
  4. It can cater for a plethora of complex custom types.

Links

Install

Install-Package Newtonsoft.Json -Version 12.0.3

Example

var array = new[] {12, 3, 4, 5};

// serialize it
var stringData = JsonConvert.SerializeObject(array);

// write to file
File.WriteAllText("FileName", stringData);

// read from file
var dataFromFile = File.ReadAllText("FileName");

// convert it back
var yourArrayAgain = JsonConvert.DeserializeObject<string[]>(dataFromFile);

// prove it
Console.WriteLine(string.Join(",", yourArrayAgain));

Output

12,3,4,5

Contrived online demo here

First you need to read the file

string text = File.ReadAllText(txtDocumentname);

Then split it into substrings, based on your delimiter:

string[] fields = text.Split(';');

Then convert the fields into integers:

int[] integers = fields.Select( x => int.Parse(x) ).ToArray();
Related