Windows Forms: How to Read text file and Sort list in C#

By FoxLearn 7/4/2017 9:55:52 PM   6.75K
How to read text (*.txt) file and sort list/array data in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadTextFileAndSort" and then click OK

c# read text fileStep 2: Design your form as below

read text file in c#

Step 3: Add code to button click event handler as below

private void btnOpen_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents(*.txt)|*.txt", ValidateNames = true, Multiselect = false })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            //Read text file
            string[] lines = System.IO.File.ReadAllLines(ofd.FileName);
            List<int> list = new List<int>();
            foreach (string s in lines)
            {
                list.Add(Convert.ToInt32(s));
                listReadFile.Items.Add(s);
            }
            //Sort list
            list.Sort();
            foreach (int x in list)
                listSort.Items.Add(x);
        }
    }
}

VIDEO TUTORIALS