开发者

C# reading a file into a 2-D array

my project is using txt file as db, each line in the txt file will be something like "abc,cdf,ghi,zkl"

now i am reading line by line from the text file and split the line into an array data[] by "," but i want to put this array into another main array called datas[], so i can store this datas[] array in memory for the whole class to use,

i dont want to fix datas[] array size as the txt file records will be growing.

what can i do in this case? i tried to make datas[] as arraylist then stored data[] array in it , but error showed.

class user
{
    ArrayList userDatas = new ArrayList();

    public user()
    {
        readUsers();
    }

    public void readUsers()
    {
        string line;

        StreamReader sr = new StreamReader("user.txt", System.Text.Encoding.Default);

        while ((line = sr.ReadLine())开发者_如何学Go != null)
        {
            ArrayList temp = new ArrayList();
            string[] rc = line.Split('|');
            for (int i = 0; i < rc.Length; i++)
            {
                temp.Add(rc[i]);

            }
            userDatas.Add(temp);
        }

    }

    public bool login(string ic, string password)
    {
        for (int i = 0; i < userDatas.Count; i++)
        {
            ArrayList temp = userDatas;
            if ((temp[1] == ic) && (temp[2] == password))
            {
                return true;
            }
        }
        return false;
    }
}


Of course if you don't mind being a little cute you should be able to do it with one line coutesy of LINQ:

string[][] LinesSplitByComma = File.ReadAllLines("file path").Select(s => s.Split(',')).ToArray();


Instead of ArrayList, use List<string> for temp and List<string[]> for userDatas.

When you're done filling them, you can convert to an array by simply calling userDatas.ToArray()

Also, your error might be here:

ArrayList temp = userDatas;
if ((temp[1] == ic) && (temp[2] == password))
{
      return true;
}

You're not first checking to make sure temp has 3 or more elements before referencing indexes 1 and 2. Also, why are you creating temp only to assign it to userDatas? Why not just say:

if (userDatas.Count() >= 3 && (userDatas[1] == ic) && (userDatas[2] == password))
   return true;

EDIT

As requested, here's my original code, though you already have much of it written, but here it is (you're code didn't show up at first):

        StreamReader reader = new StreamReader();
        List<string[]> datas = new List<string[]>();
        List<string> data = new List<string>();
        string line;
        while (!reader.EndOfStream) {
            line = reader.ReadLine();
            datas.Add(line.Split(','));
        }

        string[] datas_array = datas.ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜