简单举个例子: 
比如有一个文本文件,a.txt.里面的数据是这样的
1
2
3
4
5
6
10
102
43
543
65
76
85
等等... ... 行数未知我现在想把每一行的值取出来放在一个数组 int[] num 中.
但数组元素未知,只能等while循环后才能知道,该如何处理,能不能在一次循环内搞定.
using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                //如何处理?
            }
        }

解决方案 »

  1.   

    使用ArrayList al = new ArrayList();
      

  2.   

    List<int> list = new List<int>();
    list.Add(int a);
      

  3.   

    先用List<T>将数据放进去,然后循环完以后再 T[] = list.ToArray();
      

  4.   

    先用List<T> 然后 ToArray() 就可以了
      

  5.   

    给个简单方法:
    private void button1_Click(object sender, EventArgs e)
    {
        StreamReader reader = new StreamReader(@"E:\test.txt");
        string[] str = System.Text.RegularExpressions.Regex.Split(reader.ReadToEnd(), @"\r\n");
        int[] result;
        result = Array.ConvertAll<string,int>(str,new Converter<string,int>(toInt));
    }
    int toInt(string str)
    {
        return Int32.Parse(str);
    }
      

  6.   

    List<int> listNum = new List<int>();using (StreamReader sr = File.OpenText(path))
    {
        string s = "";    while ((s = sr.ReadLine()) != null)
        {
            listNum.Add(int.Parse(s));
        }
    } int[] num = listNum.ToArray();