Loading ...

Write Text file in ASP.NET | CodeAsp.Net

Write Text file in ASP.NET

 /5
0 (0votes)

In this blog I will explain how to write a text file in ASP.NET.

Here is my code:-

There is a Textbox and one button. You can type your name in textbox and it will write into your text file.
You can check your text file in D drive (D:\).

ASPX Code:-

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
        <tr>
            <td>Enter Your Name: </td>
            <td><asp:TextBox runat="server" ID="txtName"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2"><asp:Button runat="server" ID="btnWriteTxtFile" Text="Click" 
                    onclick="btnWriteTxtFile_Click" /></td>
        </tr>
        </table>
    </div>
    </form>
</body>
</html>

 

CodeBehind Code:-

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class writeTextFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnWriteTxtFile_Click(object sender, EventArgs e)
    {
        string textFile = string.Format("{0}.txt", DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss"));
        System.IO.StreamWriter streamWriter = File.CreateText(string.Format(@"{0}{1}", "D:\\", textFile));
        streamWriter.WriteLine(txtName.Text);
        streamWriter.Close();
    }
}

 

string.Format("{0}.txt", DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss"));--- In this code I am genreating
a different name for text file.
Example - 03-28-2010_14-49-11.txt

File.CreateText(string.Format(@"{0}{1}", "D:\\", textFile));  Here I am creating a text file and passing
PATH parameter in CreateText() Method.

streamWriter.WriteLine(txtName.Text); - Till now I have created a txt file and now I am writng
text(your name) in textfile.

 

Note – we have to use System.IO namespace.

Comments (2)

   
dimple
dimple
thank you so much...
5/14/2010
 · 
by
   
mohit
Welcome Dimple
7/4/2010
 · 
by
  • :*
  • :*
  • :
 *

Top Posts