Как связать выбор файла пользователя с StringSplit - PullRequest
0 голосов
/ 02 апреля 2019

Я пытаюсь разделить выбранный пользователем файл на массив, который разделяется, и /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();

    }

1 Ответ

1 голос
/ 02 апреля 2019
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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...