Reputation: 377
i was tring to write txt file data to a textbox, but it shows my data as one word without spaces. How do I write txt file content to a textbox and save its formatting? There is the code i tried:
private void WriteData()
{
if (File.Exists(Server.MapPath("App_Data/U3.txt")))
{
TextBox1.Text = File.ReadAllText(Server.MapPath("App_Data/U3.txt"));
}
File.WriteAllText(Server.MapPath("App_Data/U3.txt"), TextBox1.Text);
}
Edit: apparently it doesnt remove spaces, but new lines are gone and its all in one line Edit 2: alright now im trying to use ReadAllLines but how do i make this statement valid
TextBox1.Text = File.ReadAllLines(Server.MapPath("App_Data/U3.txt"));
Upvotes: 1
Views: 3507
Reputation: 82
First go to properties and change Textmode to Multi line and then try below code. It works.
protected void Page_Load(object sender, EventArgs e)
{
string file = "test.txt";
string[] str = null;
if (File.Exists(Server.MapPath(file)))
{
str = File.ReadAllLines(Server.MapPath(file));
}
foreach (string s in str)
{
TextBox1.Text = TextBox1.Text +"\n" +s;
}
}
Upvotes: 2
Reputation: 101
Maybe you can try to replace all newlines in the file output to <br/>
tags, like this:
mystring.Replace(System.Environment.NewLine, "<br />");
ps. I found that answer here: text in the textbox doesnt retain its format
Upvotes: 0