[英]How to use the array of strings and display it line by line
如何顯示已添加到列表中的內容,並逐行顯示在文本框中? 我正在將文本文件中的數據添加到列表中,以便可以在每行之后添加文本。
private void button1_Click(object sender, EventArgs e)
{
try
{
var list = new List<string>();
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
list.Add(line);
}
}
TextBox.Text = string.Join(Environment.NewLine, list.ToArray());
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred" + ex.Message);
}
}
就像是:
aTextbox.Text = string.Join(Environment.NewLine, list.ToArray());
這將獲取數組中的每個字符串,並在它們之間添加換行符。
如果只需要在TextBox
顯示文件源,則無需先將數據保存在List<string>
。 做就是了:
string text = "";
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
text += line + Environment.NewLine;
}
}
aTextbox.Text = text;
另一種方法-無需循環遍歷文件中的所有行。
using System.IO;
private void WriteFileContentsToTextBox(string filePath)
{
// Always check for existence of the file
if (File.Exists(filePath))
{
// Open the file to read from.
string[] readText = File.ReadAllLines(filePath, Encoding.UTF8);
myMultilineTextBox.Text = string.Join(Environment.Newline, readText);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.