2011-12-11 41 views
1

,當我嘗試讀取一個用阿拉伯文寫的格式文件,我只得到最後一行...什麼問題。讀非英語文件

代碼:

// Read the file and display it line by line in text box 
System.IO.StreamReader file = 
    new System.IO.StreamReader("arabic.txt", Encoding.UTF8); 
while ((line = file.ReadLine()) != null) 
{ 
    txtfile[count] = line; 
    textBox1.Text = txtfile[count]+Environment.NewLine; 

    count++; 
} 

file.Close(); 
+4

這有什麼做的文件的格式。在閱讀文章時,您將逐行替換文本框的文本。 – Foole

+0

我也建議改變你正在使用保存了數據的數據結構。好像你正在使用一個動態創建的數組(txtfile) - 你應該使用'ArrayList'或類似的東西。 – Shai

+0

感謝您的建議 –

回答

4

嘗試textBox1.Text += txtfile[count]+Environment.NewLine;

+0

非常感謝您的建議,我發現了這個微不足道的錯誤。我現在嘗試什麼,我不能當數組顯示空的沒有任何東西顯示? –

2

你只能看到你的文本框最後一行的原因是因爲你沒有追加的文本。

使用

textBox1.Text += txtfile[count]+Environment.NewLine; 

而不是

嘗試
textBox1.Text = txtfile[count]+Environment.NewLine; 
+0

由於這是工作 –

0

問題是

textBox1.Text = txtfile[count]+Environment.NewLine 

嘗試

textBox1.Text += txtfile[count]+Environment.NewLine 
0

喲ü可以嘗試這樣

System.IO.StreamReader file = 
     new System.IO.StreamReader("arabic.txt", Encoding.UTF8); 
    while ((line = file.ReadLine()) != null) 
    { 
     txtfile[count] = line; 
     textBox1.Text += txtfile[count]+Environment.NewLine; 


     count++; 
    } 

    file.Close(); 
0

在你的代碼不將行添加到文本框,您只需設置它。所以只會顯示最後一行。更改代碼這樣的:

// Read the file and display it line by line in text box 
System.IO.StreamReader file = new System.IO.StreamReader("arabic.txt", Encoding.UTF8); 
while ((line = file.ReadLine()) != null) 
{ 
    txtfile[count] = line; 
    textBox1.Text += txtfile[count]+Environment.NewLine; 

    count++; 
} 

file.Close(); 
1

你可以試試,

TextBox1.Text=System.IO.File.ReadAllText("arabic.txt",Encoding.UTF8); 
0

個人而言,我想讀取文件的集合 - 例如,一個列表<> - 它分配給我的文本框,而不是以前的設置它在閱讀後直接到文本框(文本框中沒有顯示的所有內容 - 即最後一行之後的所有內容 - 實際上都丟失了)。

此外,使用StreamReaders時,使用using語句;之後本身清理刪除調用StreamReader.Close()當我們完成的需要:

public List<string> ReadTextFile(string filePath) 
{ 
    var ret = new List<string>(); 

    if (!File.Exists(filePath)) 
     throw new FileNotFoundException(); 

    // Using the "using" directive removes the need of calling StreamReader.Close 
    // when we're done with the object - it closes itself. 
    using (var sr = new StreamReader(filePath, Encoding.UTF8)) 
    { 
     var line; 

     while ((line = sr.ReadLine()) != null) 
      ret.Add(line); 
    } 

    return ret; 
} 

你也可以使用一個數組,或任何其他集合。用這種方法,你可以填寫你的TextBox元素,像這樣:

var fileContents = ReadTextFile("arabic.txt"); 

foreach (var s in fileContents) 
    textBox1.Text += string.Format("{0}{1}", s, Environment.NewLine); 

同時還具有在fileContents文本文件的本地副本。

+0

非常感謝玉米粥的建議。我直接寫入文本框,以確保它可以讀取和顯示阿拉伯文垃圾。但我希望這個阿拉伯語文件在其中搜索關於單詞從用戶輸入文本框中。你能幫助我嗎?我注意到你使用格式(「{0} {1}」==>這是什麼? –

+0

String.Format將指定字符串中的每個格式項替換爲相應對象值的文本等同意義如果你願意例如'字符串。格式(「Value:{0},obj.Value」);',假設obj.Value是10,則輸出將是'Value:10'。 「{0}」僅僅是對象值的通配符,該值在方法的參數中指定。 – aevitas