读取文本文件C#中特定列的数据

时间:2016-03-12 13:21:20

标签: c# file text

我是C#的新手,希望你能帮助我。我的文本文件包含行数据,列由制表符分隔。见下面的例子。我的问题:如何从第三栏中读取数据。

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

我当前的代码读完整行:

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

3 个答案:

答案 0 :(得分:1)

function startFadeEffect(elem){
    var opacSetting = noOpac / 10;
    if(noOpac > 10){
        opacSetting = 1;    
    }
    elem.style.opacity = opacSetting;   
    elem.style.display = "block";
    noOpac++;
    var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
    if(opacSetting == 1){
        clearTimeout(timer);
        elem.style.opacity = 1;
        noOpac = 0;
        setTimeout(function() { endFadeEffect(elem); }, delay/2);
    }
}

function endFadeEffect(elem){
    var opacSetting = fullOpac / 10;
    if(fullOpac < 0){
        opacSetting = 0;    
    }
    elem.style.opacity = opacSetting;   
    fullOpac--;
    var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
    if(opacSetting == 0){
        clearTimeout(timer);
        elem.style.opacity = 0;
        elem.style.display = "none";
        fullOpac = 10;
        return false;
    }
}

答案 1 :(得分:0)

我建议使用CsvHelper(http://joshclose.github.io/CsvHelper/

var csv = new CsvReader( textReader );
while( csv.Read() )
{
    var intField = csv.GetField<int>( 2 ); // index is 0 based
}

答案 2 :(得分:0)

您可以这样做:

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分隔,则需要使用:

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

希望它有所帮助。