首页 > 解决方案 > 如何将用户文件选择链接到 StringSplit

问题描述

我试图让用户选择的文件拆分为一个由 和 /t 分隔的数组。

用户可以在代码顶部选择一个文件,但是当他们按下 ValidateButton 时,我如何让他们的选择拆分为一个较低的数组

文本文件或以这种方式排序

信息,信息,信息,
信息,信息,信息,
信息,信息,信息,

如果我可以将它们放入一个数组中,那么我可以轻松地组织数据。

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = @"C:\"; // Start in C: drive
        openFileDialog1.Title = "Browse Text Files";
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.DefaultExt = "txt"; // Extension of file is txt 
        openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files 
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            FileNameBox.Text = openFileDialog1.FileName; // Chosen file name is displayed in text box

            var fileStream = openFileDialog1.OpenFile();

            using (StreamReader reader = new StreamReader(fileStream))
            {
                var fileContent = reader.ReadToEnd();
            }
        }


    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        //This is the file path the user has chosen
    }

    public void ValidateButton_Click(object sender, EventArgs e)
    {


        //Call Multi line text box
        //Call PROGRESS BAR_


        int counter = 0;
        string lines;


        string Patient = lines;

        string[] split = Patient.Split(new Char[] { ',', '\t' });

        foreach (string s in split)


            if (s.Trim() != "")
                Console.WriteLine(s);
            {
                Console.WriteLine(lines);
                counter++;
            }
            Console.WriteLine("There were {0} records.", counter);
            Console.ReadKey();

    }

标签: c#winforms

解决方案


List<string> temp = new List<string>();
string[] finalArray;

using (StreamReader reader = new StreamReader(fileStream))
{
    // We read the file then we split it.
    string lines = reader.ReadToEnd();
    string[] splittedArray = lines.Split(',');    

    // We will check here if any of the strings is empty (or just whitespace).
    foreach (string currentString in splittedArray)
    {
        if (currentString.Trim() != "")
        {
            // If the string is not empty then we add to our temporary list.
            temp.Add(currentString);
        }
    }

    // We have our splitted strings in temp List.
    // If you need an array instead of List, you can use ToArray().
    finalArray = temp.ToArray();
}

推荐阅读