我有这部分代码,它接受一个文件并将其放入ArrayList.将要输入的文件是CSV(CSV我使用的当前第一行的标题,所以我不需要该行),第二行必须放入ArrayList.
我使用ArrayList是因为文件可以是动态的,所以我不确定第二行的长度是多少.我测试了(使用在第二行上有7个逗号分隔值的文件)此代码,并打印出ArrayList有长度(fileList.Count)= 1.
怎么了 ?
ArrayList fileList2 = new ArrayList();
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
textBox3.Text = filename;
string line2;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text); //reads file from textbox
stringforData = file2.ReadLine(); // this reads the first line that I dont need
while ((line2 = file2.ReadLine()) != null) //read the lines
{
// puts elements into array
fileList2.Add(line2.Split(';'));//split the line and put it in the arraylist
}
file2.Close();
if (true) // this is for testind what is happening
{
this.textBox2.Clear();
textBox3.Text = Convert.ToString(fileList2.Count);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你不想使用fileList2.AddRange()而不是fileList2.Add()吗?在我看来,你现在正在向fileList添加一个项目.该项目是一个数组,其中包含您实际想要添加到列表中的所有项目.如果你先得到那个数组而不是使用addRange方法,那应该没问题.