In this article i will illustrate how to create text file , write and append text to it using C#.
Aspx Code :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SaveTextToaFile.aspx.cs" Inherits="Forum_Topics_SaveTextToaFile" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>SAVING TEXT TO A FILE</title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td> Write few words about you: </td> <td> <asp:TextBox ID="txtAboutYou" runat="server" TextMode="MultiLine"></asp:TextBox> </td> </tr> <tr> <td colspan="2" align="center"> <asp:Button ID="btnSaveText" runat="server" Text="SaveText" OnClick="btnSaveText_Click" /> </td> </tr> <tr> <td colspan="2" align="left"> <asp:Label ID="lblMsg" runat="server" ForeColor="Red" ></asp:Label> </td> </tr> </table> </div> </form> </body> </html> |
Code Behind :
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public partial class Forum_Topics_SaveTextToaFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSaveText_Click(object sender, EventArgs e) { /*FILE NAME OR PATH TO FILE*/ string Filename = "C:\\Users\\Administrator\\Desktop\\Profile.txt"; //CHECK FOR FILE EXISTENCE if (!File.Exists(Filename)) { //CREATE FILE StreamWriter txtFile = File.CreateText(Filename); txtFile.Close(); //APPEND TEXT txtFile = File.AppendText(Filename); txtFile.WriteLine(txtAboutYou.Text); txtFile.Close(); } else //APPEND TEXT File.AppendAllText(Filename, txtAboutYou.Text); lblMsg.Text = "Text is saved"; } } |
thank you so much brother for sharing your knowledge , i have used your code in my project and working properly thanks alot
ReplyDelete