开发者

Cant split a line

开发者 https://www.devze.com 2023-04-11 17:03 出处:网络
I have this part of code that takes a file and puts it in an ArrayList. The file that will be entered will be a CSV (the current CSV that I use has headers at the first line, so I don\'t need that lin

I have this part of code that takes a file and puts it in an ArrayList. The file that will be entered will be a CSV (the current CSV that I use has headers at the first line, so I don't need that line) and the second line has to be put in an ArrayList.

I use ArrayList because the file can be dynamic, so I am not sure what will be the length of the second line. I tested (with a file that has 7 comma-separated values on the second line) this code and it prints that the ArrayList has a length (fileList.Count) = 1.

What is wrong ?

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.I开发者_StackOverflow中文版O.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);
        }
    }
}


Don't you want to use fileList2.AddRange() instead of fileList2.Add() ? It seems to me that you are adding one item to the fileList now. That item is an array that contains all items you actually wanted to add to the list. If you get that array first and than use the addRange method, It should be fine.


First off, you should probably be using AddRange(), not Add(). Second, if this is a CSV file, then why are you passing a semi-colon to the split() method?

0

精彩评论

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

关注公众号