2017-06-14 34 views
0

因此,我試圖用streamreader讀取文本文件的每一行,從那裏我進入while循環以獲取文件的結尾for循環將每個令牌打印到列表框中。我覺得這應該工作!找到.txt文件中的所有單詞c#

編輯:我的問題是如何讀取選定的文件,單詞,並將它們打印到列表框?

if (openFile.ShowDialog() == DialogResult.OK) 
      { 
       StreamReader inputFile; 
       inputFile = File.OpenText(openFile.FileName); 
       string line; 
       //int totalWords; 

       char[] delim = { '.', '!', '?', ',', '(', ')' }; 

       while (!inputFile.EndOfStream) 
       { 
        line = inputFile.ReadLine(); 
        string[] tokens = line.Split(delim); 
        for (int i = 0; i < tokens.Length; i++) 
        { 
         wordListBox.Items.Add(tokens[i]); 
        } 
       } 
       inputFile.Close(); 
      } 
+6

那麼,你的問題是什麼?你想知道我們是否有同樣的感覺? – CharithJ

+0

我會在使用塊中使用StreamReader。例如:使用(StreamReader inputFile = File.OpenText(openFile.FileName)) – CharithJ

+1

從[help/on-topic]:*尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需的行爲,一個特定的問題或錯誤,以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者沒有用處。*我沒有看到*特定問題或錯誤*(我甚至沒有看到含糊不清的問題)。我也沒有看到任何問題。您可能需要花幾分鐘時間閱讀[問],然後回來並[編輯]您的文章以使其更加清晰。 –

回答

-1

This Does work .... mostly。 txt文檔仍然在後臺運行。但是新行(\ n)和(\ t)不與分隔符分開。爲此我相信需要使用拆分功能。

感謝您的幫助。

+0

把這個信息的問題。它的意思並不清楚你的意思 – pm100

+0

這不是一個答案。請更新您的問題或對問題的評論。 –

1

如果將空格字符'\n','\r','\t'' '添加到您的分隔符數組中,該怎麼辦?然後,您可以撥打File.ReadAllText,它將整個文件作爲字符串返回,並將其拆分到您的定界符(刪除空條目時)。

之後,你有話的數組,你可以添加到您的ListBox:如果你試圖填補使用的StreamReader從文件中的單詞列表框

if (openFile.ShowDialog() == DialogResult.OK) 
{ 
    char[] delims = { '.', '!', '?', ',', '(', ')', '\t', '\n', '\r', ' ' }; 

    string[] words = File.ReadAllText(openFile.FileName) 
     .Split(delims, StringSplitOptions.RemoveEmptyEntries); 

    foreach (string word in words) 
    { 
     wordListBox.Items.Add(word); 
    } 
} 
0

- 你應該想想,因爲StreamReader的是用於文件/網絡流情況下,處理大文件或網絡延遲/傳播等。如果你有一個大文件 - 填充ListBox太多的項目是一個好習慣嗎?我不這麼認爲。但是,根據你的問題,如果你想用StreamReader來做,請檢查這個實現:

 string filename = @"D:\text.txt"; 
     var words = new List<string>(); 
     char[] delims = { '.', '!', '?', ',', '(', ')', '\t', '\n', '\r', ' ' }; 

     try 
     { 
      using (var reader = new StreamReader(filename)) 
      { 
       while (!reader.EndOfStream) 
       { 
        var line = reader.ReadLine(); 
        words.AddRange(line.Split(delims, StringSplitOptions.RemoveEmptyEntries)); 
       } 
      } 
     } 

     // now you dont need to close stream because 
     // using statement will handle it for you 

     catch // appropriate exception handling 
     { 

     } 

     foreach (string word in words) 
     { 
      wordListBox.Items.Add(word); 
     } 
相關問題