如何使用C#解析文本文件?

时间:2011-01-26 14:29:43

标签: c# winforms string

我想创建一个Windows窗体应用程序,它将读入文本文件并将文本文件的字段放入文本框中。

文本文件格式示例:

Name;Surname;Birthday;Address

Name;Surname;Birthday;Address

的Winforms

Name: textboxname

Surname: textboxsurname

Birthday: textboxbirth

Address: textboxaddress

我还希望这个Winforms应用程序有一个NextBack按钮,以便循环显示记录。

我不知道如何在C#中执行此操作。我从哪里开始?

4 个答案:

答案 0 :(得分:5)

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]
}

这比Fredrik的代码简单一点,但它一次读取文件。这通常很好,但会导致非常大的文件出现问题。

答案 1 :(得分:2)

以简单的形式,您逐行阅读文件,拆分;上的每一行并使用以下值:

// 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);
}

另外,请查看CSVReader哪个库便于处理这些文件。

答案 2 :(得分:2)

这是一个简单的示例,演示如何使用VB.NET TextFieldParser解析CSV文件。为什么选择TextFieldParser?因为它是最完整的CSV解析器,它已经安装在.NET中。

它还显示了数据绑定在Windows窗体中的工作原理。阅读文档以获取更多信息,这只是为了帮助您入门。

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;
    }
}

答案 3 :(得分:0)

基本上你必须

  • 阅读文件(File.ReadAllLines)
  • 创建记录列表(1条记录= 1套姓名,姓氏,生日)
  • 解析阅读文本并用记录填写列表
  • 创建表单并将获取的数据传递给此表单
  • 创建您自己的UserControl =一组文本框以查看您的数据+几个按钮(FW和BW)

这是一个非常复杂的问题。