【问题标题】:How do I parse a text file using C#?如何使用 C# 解析文本文件?
【发布时间】:2011-01-26 14:29:43
【问题描述】:

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

文本文件格式示例:

Name;Surname;Birthday;Address

Name;Surname;Birthday;Address

Winform

Name: textboxname

Surname: textboxsurname

Birthday: textboxbirth

Address: textboxaddress

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

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

【问题讨论】:

标签: c# winforms string


【解决方案1】:
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 的代码稍微简单一点,但它会一次读取所有文件。这通常很好,但会导致非常大的文件出现问题。

【讨论】:

  • 在 .NET 4 中,您可以使用 File.ReadLines 而不是 File.ReadAllLines,它会逐行读取。
  • @Danko:很好。这提供了两全其美的效果。 File.ReadLines 也可用于 .NET 3.5。
【解决方案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,这是一个便于处理此类文件的库。

【讨论】:

  • 不错的答案...谢谢,我会尝试,但我怎样才能制作下一个和后退按钮?
  • @matthias:你会想为此使用一个单独的问题。但是,我建议您只查找基本的 C# Webforms 教程。
【解决方案3】:

这是一个简单的示例,展示了如何使用 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;
    }
}

【讨论】:

    【解决方案4】:

    基本上你必须

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

    这是一个相当复杂的问题。

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多