如何使用 C# 解析文本文件? [英] How do I parse a text file using C#?

查看:42
本文介绍了如何使用 C# 解析文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

文本文件格式示例:

Name;Surname;Birthday;Address

Name;Surname;Birthday;Address

Winforms

Name: textboxname

Surname: textboxsurname

Birthday: textboxbirth

Address: textboxaddress

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

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

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

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

推荐答案

在一个简单的形式中,你逐行读取文件,在 ; 上拆分每一行并使用值:

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

此外,请查看 CSVReader,这是一个有助于处理此类文件的库.

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

这篇关于如何使用 C# 解析文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆