简体   繁体   中英

How do I parse a text file using C#?

I'd like to make a Windows Forms application that will read in a text file and put the fields of the text file into textboxes.

Example of text file format:

Name;Surname;Birthday;Address

Name;Surname;Birthday;Address

Winforms

Name: textboxname

Surname: textboxsurname

Birthday: textboxbirth

Address: textboxaddress

I also want this Winforms application to have a Next and Back button so it can cycle through the records.

I don't know how to do this in C#. Where do I start?

foreach (string line in File.ReadAllLines("path-to-file"))
{
    string[] data = line.Split(';');
    // "Name" in data[0] 
    // "Surname" in data[1] 
    // "Birthday" in data[2] 
    // "Address" in data[3]
}

This is a tiny bit simpler than Fredrik's code, but it reads the file all at once. This is usually fine but will cause issues for very large files.

In a simple form, you read the file line by line, split each line on ; and use the values:

// open the file in a way so that we can read it line by line
using (Stream fileStream = File.Open("path-to-file", FileMode.Open))
using (StreamReader reader = new StreamReader(fileStream))
{
    string line = null;
    do
    {
        // get the next line from the file
        line = reader.ReadLine();
        if (line == null)
        {
            // there are no more lines; break out of the loop
            break;
        }

        // split the line on each semicolon character
        string[] parts = line.Split(';');
        // now the array contains values as such:
        // "Name" in parts[0] 
        // "Surname" in parts[1] 
        // "Birthday" in parts[2] 
        // "Address" in parts[3] 

    } while (true);
}

Also, check out CSVReader which is library facilitating the handling of files like these.

Here is a simple example that shows how to parse a CSV file using VB.NET TextFieldParser. Why TextFieldParser? Because it's the most complete CSV parser out there and it's already installed in .NET.

It also shows how data binding works in Windows Forms. Read the documentation for more information, this is just to get you started.

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;

public class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    DataTable records;
    BindingSource bindingSource;

    public Form1()
    {
        // Create controls
        Controls.Add(new Label { Text = "Name", AutoSize = true, Location = new Point(10, 10) });
        Controls.Add(new TextBox { Name = "Name", Location = new Point(90, 10) });
        Controls.Add(new Label { Text = "Sirname", AutoSize = true, Location = new Point(10, 40) });
        Controls.Add(new TextBox { Name = "Sirname", Location = new Point(90, 40) });
        Controls.Add(new Label { Text = "Birthday", AutoSize = true, Location = new Point(10, 70) });
        Controls.Add(new TextBox { Name = "Birthday", Location = new Point(90, 70) });
        Controls.Add(new Label { Text = "Address", AutoSize = true, Location = new Point(10, 100) });
        Controls.Add(new TextBox { Name = "Address", Location = new Point(90, 100), Size = new Size(180, 30) });
        Controls.Add(new Button { Name = "PrevRecord", Text = "<<", Location = new Point(10, 150) });
        Controls.Add(new Button { Name = "NextRecord", Text = ">>", Location = new Point(150, 150) });

        // Load data and create binding source
        records = ReadDataFromFile("Test.csv");
        bindingSource = new BindingSource(records, "");

        // Bind controls to data
        Controls["Name"].DataBindings.Add(new Binding("Text", bindingSource, "Name"));
        Controls["Sirname"].DataBindings.Add(new Binding("Text", bindingSource, "Sirname"));
        Controls["Birthday"].DataBindings.Add(new Binding("Text", bindingSource, "Birthday"));
        Controls["Address"].DataBindings.Add(new Binding("Text", bindingSource, "Address"));

        // Wire button click events
        Controls["PrevRecord"].Click += (s, e) => bindingSource.Position -= 1;
        Controls["NextRecord"].Click += (s, e) => bindingSource.Position += 1;
    }

    DataTable ReadDataFromFile(string path)
    {
        // Create and initialize a data table
        DataTable table = new DataTable();
        table.Columns.Add("Name");
        table.Columns.Add("Sirname");
        table.Columns.Add("Birthday");
        table.Columns.Add("Address");

        // Parse CSV into DataTable
        using (TextFieldParser parser = new TextFieldParser(path) { Delimiters = new String[] { ";" } })
        {
            string[] fields;
            while ((fields = parser.ReadFields()) != null)
            {
                DataRow row = table.NewRow();
                for (int n = 0; n < fields.Length; n++)
                    row[n] = fields[n];
                table.Rows.Add(row);
            }
        }

        return table;
    }
}

Basically you have to

  • Read the file (File.ReadAllLines)
  • Create list of records (1 record = 1 set of name,surname,birthday)
  • Parse the read text and fill the list with records
  • Create a Form and pass the acquired data to this form
  • Create your own UserControl = set of textboxes to view your data + few buttons (FW and BW)

It's quite a complex question.

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