To Read and Write to Text file from ASP.NET
To Write C# code
If the file does not exist you will get an error. You can check to see if the file exists using this code:
if (System.IO.File.Exists(Server.MapPath("test.txt")))
To write the contents of a TextBox control to a text file using the System.IO.StreamWriter class use the following code:
System.IO.StreamWriter StreamWriter1 =
new System.IO.StreamWriter(Server.MapPath("test.txt"));
StreamWriter1.WriteLine(TextBox1.Text);
StreamWriter1.Close();
Inserting "\r\n" will create a line break in the text file. Adding line breaks from code can be done using this code:
StreamWriter1.WriteLine("Some text on line1.\r\nSome text on line2.");
To Read c# code
System.IO.StreamReader StreamReader1 =
new System.IO.StreamReader(Server.MapPath("test.txt"));
TextBox2.Text = StreamReader1.ReadToEnd();
StreamReader1.Close();
If the file does not exist you will get an error. You can check to see if the file exists using this code:
if (System.IO.File.Exists(Server.MapPath("test.txt")))
To write the contents of a TextBox control to a text file using the System.IO.StreamWriter class use the following code:
System.IO.StreamWriter StreamWriter1 =
new System.IO.StreamWriter(Server.MapPath("test.txt"));
StreamWriter1.WriteLine(TextBox1.Text);
StreamWriter1.Close();
Inserting "\r\n" will create a line break in the text file. Adding line breaks from code can be done using this code:
StreamWriter1.WriteLine("Some text on line1.\r\nSome text on line2.");
To Read c# code
System.IO.StreamReader StreamReader1 =
new System.IO.StreamReader(Server.MapPath("test.txt"));
TextBox2.Text = StreamReader1.ReadToEnd();
StreamReader1.Close();
Comments