2013-12-18 15 views
1

Hye there!我對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 

突出顯示的文本上面已經制表符,所以我不需要他們。請爲此提出任何解決方案。我只需要這些詞就像標題:|生命體徵| | monitor |並| |檢查|等等...有人可以幫我請這個嗎?

+1

除非你發佈的代碼比你的實際代碼不同,您的富文本框只會顯示不包含選項卡的最後一行:'richbox.Text = line;'您需要**將每個適當的行追加到富文本框 –

+0

不,它不起作用根本! :( – user3115728

回答

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

您可以使用此方法

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

這將仍然只是不斷覆蓋在閱讀的最後一行richbox中的文本,而不是所有的文件所需的數據。 – krillgar

+0

我見過它。但我不知道爲什麼user3115728接受我的答案 – cosset

+1

是的,我對同樣的事情很好奇,也許我們應該向OP推薦一個「拒絕接受答案」功能,如果這樣做沒有任何意義,那麼你至少應該拿到一個可以接受的標誌有負面評價的答案;) – krillgar

1

krillgar的答案已經解釋了爲什麼你的例子不工作,但這裏是所有的代碼作爲一個襯墊,只是爲了好玩:

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

完全同意。然而,正如他們所說,他們是C#的全新人物,而且他們的方法根本沒有其他的LINQ,所以我不想混淆OP。 – krillgar