读取文本文件,跳过其中包含TAB字符的行

时间:2013-12-18 15:09:59

标签: c# delimiter tab-delimited-text

谢谢那里!我对C#完全不熟悉并且需要知道如何逐行读取文件(跳过那些带有制表符的文件)并将文本设置为RichTextBox! 我一直这样做:

DialogResult result = open_dialog.ShowDialog();

if (result == DialogResult.OK)
{
    string file_name = open_dialog.FileName;
    System.IO.StreamReader sr = new System.IO.StreamReader(file_name);
    String data;

    data = sr.ReadToEnd();
    rich_words.Text = data;

    String line;

    using (var file = System.IO.File.OpenText(fileName))
    {
        // read each line, ensuring not null (EOF)
        while ((line = file.ReadLine()) != null)
        {
            if(line.Contains('\t'))
                //do nothing
            else
                richbox.Text=line;
        }
    }
}

但我没有这样做!它很伤心,因为我已经尽了最大努力,现在似乎没有什么事情由我完成! 我的样本数据是:

生命体征

                respirations    
           vital signs  
           vital sign checks    
           vital signs/blood pressure   
               blood pressure observation
               blood pressure
               auscultate blood pressures
               monitor blood pressure
               check blood pressure
               blood pressure gauge

显示器

           monitor skin color   
           monitor characteristics  
           monitor pulse    
           monitor presence 
           monitor  
           monitor/monitor temperature  
               monitor temperature
               continuous temperature monitoring device

检查

           check body temperature   
           check frequency  
           check pain level 
           special checks   
           check    
           check body temperaturewith   

上面突出显示的文字有制表符,所以我不需要它们。请为此建议任何解决方案。我只需要像标题一样的字:|生命体征| |显示器|并|检查|等等......有人可以帮我吗?

3 个答案:

答案 0 :(得分:2)

DialogResult result = open_dialog.ShowDialog();
if (result == DialogResult.OK) {
    StreamReader sr = new StreamReader(open_dialog.FileName);

    StringBuilder() sb = new StringBuilder();

    // Don't set the rich_words.Text = data here because there's no need to.

    string line;
    using (var file = File.OpenText(dialog.FileName)) {
        while ((line == file.ReadLine()) != null) {
            if (!line.Contains('\t')) {
                sb.AppendLine(line);
            }
            // No need to have an else since we only want to do stuff when the line does not contain a tab.
        }
    }

    // Now that you have all of the text from the file into your StringBuilder, you add it as the text in the box.
    rickbox.Text = sb.ToString();
}

每当一行不包含标签时,您所做的就是更改文本框中的文本。你覆盖了一切。

答案 1 :(得分:1)

krillgar的回答已经解释了为什么你的例子不起作用,但是这里的所有代码都是一个单行,只是为了好玩:

richbox.Text = String.Join(Environment.NewLine, File.ReadAllLines(file).Where(l => !l.Contains("\t")).ToArray());

答案 2 :(得分:-1)

您可以使用此方法

if(Char.IsControl(line[0]))
  //do nothing
else
  richbox.Text=line;