個人而言,我想讀取文件的集合 - 例如,一個列表<> - 它分配給我的文本框,而不是以前的設置它在閱讀後直接到文本框(文本框中沒有顯示的所有內容 - 即最後一行之後的所有內容 - 實際上都丟失了)。
此外,使用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文本文件的本地副本。
這有什麼做的文件的格式。在閱讀文章時,您將逐行替換文本框的文本。 – Foole
我也建議改變你正在使用保存了數據的數據結構。好像你正在使用一個動態創建的數組(txtfile) - 你應該使用'ArrayList'或類似的東西。 – Shai
感謝您的建議 –