Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Multidimensional Arrays Like PHP

Tags:

arrays

c#

I've been trying to do this for about 6 hours now and i'm stumped..

I want the equivalent of this in C#:


    $settings = array();
    foreach(file('settings.txt') as $l) $settings[]=explode(',',$l);
    print $settings[0][2];

This is what i've got so far that doesn't work:


    string fileName = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\" + "settings.txt";
    string[,] settings;

    FileStream file = null;
    StreamReader sr = null;

    try
    {
        file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);
        sr = new StreamReader(file, Encoding.ASCII);
        string[] line;
        int i = 0;
        do
        {
            line = sr.ReadLine().Split(',');
            settings[i++, 0] = line[0];
        } while (line != null);
        file.Close();

        MessageBox.Show(settings[1, 0]);
    } catch (Exception err) { MessageBox.Show(err.Message); }

I get "Object reference not set to an instance of an object", any ideas would be greatly appreciated..

like image 585
Dean Bayley Avatar asked Dec 06 '22 05:12

Dean Bayley


1 Answers

Use a jagged array instead of a multidimensional one – or better yet, a List<string[]>:

var settings = new List<string[]>();

foreach (string line in File.ReadLines("settings.txt", System.Text.Encoding.ASCII))
    settings.Add(line.Split(','));

Marc's use of LINQ instead of the loop is a good alternative.

like image 118
Konrad Rudolph Avatar answered Dec 09 '22 15:12

Konrad Rudolph