Pé *_*Bin 0 c# textbox for-loop while-loop
我有一个名为:blogPostTextBox的文本框和一个名为:blogMessage.txt的文件
这个blogMessage.txt包含3个文本
我想从该txt文件中读取数据,并使用for循环或while循环在blogPostTextBox中显示数据.此外,我需要在每条消息的末尾使用System.Environment.NewLine,以便每条消息显示在blogPostsTextBox中的单独行上.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
blogPostsTextBox.Text = "";
string blogMessage = File.ReadAllText(Server.MapPath("~") +
"/App_Data/blogMessages.txt");
}
}
Run Code Online (Sandbox Code Playgroud)
如何继续使用该代码?...谢谢你们!
string path = Server.MapPath("~") + "/App_Data/blogMessages.txt";
string blogMessage = String.Join(Environment.NewLine, File.ReadLines(path));
blogPostTextBox.Text = blogMessage;
Run Code Online (Sandbox Code Playgroud)
File.ReadLinesIEnumerable<string>从文件返回行(即会有三条消息).然后我连接线String.Join- 它在文本文件中找到的每一行之后添加新行.
BTW为什么你不能简单地将文件内容分配给文本框?
blogPostTextBox.Text = File.ReadAllText(path);
Run Code Online (Sandbox Code Playgroud)
更新(带循环)
string path = Server.MapPath("~") + "/App_Data/blogMessages.txt";
StringBuilder builder = new StringBuilder();
foreach(var line in File.ReadLines(path))
builder.AppendLine(line);
blogPostTextBox.Text = builder.ToString();
Run Code Online (Sandbox Code Playgroud)