读取文本文件C#中特定列的数据 [英] Read data of specific column in text file C#

查看:75
本文介绍了读取文本文件C#中特定列的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,希望您能为我提供帮助.我有一个文本文件,其中的数据疯狂地存在行,列之间由制表符分隔.请参见下面的示例.我的问题是:如何仅从第三列读取数据.

I am new to C# and hoping you can help me. I have text file with data mad of rows and the columns are separated by tabs. See example below. My question: how can read the data from just column three.

739492  3   600 3   600
739493  20  4000    3   600
739494  3   600 3   600
739495  20  4000    3   600
739496  3   600 3   600
739497  20  4000    3   600

我当前的代码读取整行:

My current code reads the full line:

private void btnRead_Click(object sender, EventArgs e)
{
    string assemblyName = Assembly.GetExecutingAssembly().Location;
    string assemblyDirectory = Path.GetDirectoryName(assemblyName);
    m_readFile = new StreamReader (assemblyDirectory + @"\" + "MyDataFile.txt");

    int counter = 1;
    string line;

    while ((line = m_readFile.ReadLine()) != null)
    {
        MessageBox.Show(line);            
        counter++;
    }

    m_readFile.Close();
}

推荐答案

您可以执行以下操作:

private void btnRead_Click(object sender, EventArgs e)
{
    string assemblyName = Assembly.GetExecutingAssembly().Location;
    string assemblyDirectory = Path.GetDirectoryName(assemblyName);
    m_readFile = new StreamReader (assemblyDirectory + @"\" + "MyDataFile.txt");

    int counter = 1;
    string line;
    while ((line = m_readFile.ReadLine()) != null)
    {
        string col = line.Split(' ')[2];
        MessageBox.Show(line);            
        counter++;
    }

    m_readFile.Close();
}

如果文本文件中的列由TAB分隔,则需要使用:

If your columns in text file are separated by TAB you need to use:

string col = line.Split('\t')[2];

希望有帮助.

这篇关于读取文本文件C#中特定列的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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