简体   繁体   中英

How to parse and use lines from a text file in C#

So I am trying to create a Windows Form program. The program is supposed to use a menustrip to open a handful of various text files containing lines of text for a student name, class, and a series of grades. The program then adds the name/class to labels on the form, and adds the grades to an array which is then used to calculate a final score. I managed to get the program to let me open the text file. I was then able to put all the information into a richtextbox.

However, now I am trying to parse out the lines and make use of them. I'm trying to divide the lines up into variables and split them where there is a comma.

I tried using the string[] textSplit = OpenFile.Split(","); but I get an error.

How can I split up the pieces of text and then how can I actually interact with each line? What should I be doing next? I'm so lost.

   private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog
        {
            InitialDirectory = @"",
            Title = "Browse Text Files",

            CheckFileExists = true,
            CheckPathExists = true,

            DefaultExt = "txt",
            Filter = "txt files (*.txt)|*.txt",
            FilterIndex = 2,
            RestoreDirectory = true,

            ReadOnlyChecked = true,
            ShowReadOnly = true
        };

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            
        }

        var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
        richTextBox1.Text = OpenFile.ReadToEnd();
        string[] textSplit = OpenFile.Split(",");


    }

The following logic might be helpful in a way you could go about actually interact with each line:

//read all lines of the file into an array

//foreach string in the array

  //split the line on comma and store in an array X

Then you can access specific words of that line using indexes

the openFile variable contains the stream of the file you're opening, You must split the text in RichTextBox. I suggest that you use using block to read the file, and then read file contents.

I have edited my answer, but in this cases you have to Model your data in a class, for example a Student class that defines your data model containing student's name, class, grades, etc. And then populate it when reading the file line by line.

To open the file using OpenFileDialog :

private string openFile() {
            using(var openFileDlg = new OpenFileDialog()) {
                openFileDlg.DefaultExt = "txt";
                openFileDlg.Filter = "txt files(*.txt)| *.txt";
                if(openFileDlg.ShowDialog() == DialogResult.OK) {
                    return openFileDlg.FileName;
                }
            }
            return null;
        }

Then you read the file by passing filename you've got from above method to it.

private void readFile(string filename) {
            string result = "";
            using (var OpenFile = new System.IO.StreamReader(filename)) {
                result = OpenFile.ReadToEnd();
            }

            richTextBox1.Text = result; //Show the whole content in RichTextBox

            using(var reader = new StringReader(result)) {
                string line = string.Empty;
                do {
                    line = reader.ReadLine();
                    if (line != null) {
                        var data = line.Split(',');
                        //You can now assing each value
                        var name = data[0]; //Suppose that the first one is Student's name
                        var className = data[1];
                        //Assign other data
                    }

                } while (line != null);
            }
        }

In the do loop, when the line is not null, you can create a new instance of Student class and assign the values to properties. It would be much cleaner.

I suggest extracting methods we can decompose the initial problem into easier one's. First, let's ask for the file name ( null if the file is not provided):

 public static string ConfigFileName() {
   using (OpenFileDialog openFileDialog1 = new OpenFileDialog() {
        InitialDirectory = @"",
        Title = "Browse Text Files",

        CheckFileExists = true,
        CheckPathExists = true,

        DefaultExt = "txt",
        Filter = "txt files (*.txt)|*.txt",
        FilterIndex = 2,
        RestoreDirectory = true,

        ReadOnlyChecked = true,
        ShowReadOnly = true  
     }) {

     // We return file name if and only if OK pressed
     return openFileDialog1.ShowDialog() == DialogResult.OK
       ? openFileDialog1.FileName
       : null;  
   }
 }

Then let's query the file data: we'll read file lines and split eachline into items. We can do it with a help of Linq

 private static string[] ConfigRecords() {
   string fileName = ConfigFileName();

   if (string.IsNullOrWhiteSpace(fileName))
     return new string[0];

   return File
     .ReadLines(fileName)
     .Where(line => !string.IsNullOrWhiteSpace(line)) // no empty lines
     .SelectMany(line => line.Split(
        new char[] { ',', ';', '\t'}, //TODO: think over delimiters
        StringSplitOptions.RemoveEmptyEntries))
     .Select(item => item.Trim()) // let's be nice and trim spaces
     .Where(item => !string.IsNullOrWhiteSpace(item)) // no empty items  
     .Distinct(StringComparer.OrdinalIgnoreCase) // remove duplicates if any
     .OrderBy(item => item, StringComparer.OrdinalIgnoreCase)
     .ToArray();
 }

Finally, you can use the methods in the UI:

 private void openToolStripMenuItem_Click(object sender, EventArgs e) {
   string[] records = ConfigRecords();

   richTextBox1.Text = string.Join(Environment.NewLine, records);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM