Follow by Email

Friday, June 7, 2013

Export String to .txt File in asp.net | Exporting String Data to text

Hi in this post i will show how to export string data into a text file in asp.net.

Below is my sample code for this:

ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="stringToNotepad.aspx.cs" Inherits="stringToNotepad" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
        <asp:Button ID="Button1" runat="server" Text="Export to text(.txt)" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class stringToNotepad : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String s;
            s = "Hello World! This is C#.net";
            Label1.Text = s;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        Response.AddHeader("content-disposition", "attachment;filename=Note.txt");
        Response.ContentType = "application/vnd.text";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        Response.Write(Label1.Text.ToString());
        Response.End();
    }
}

Result:

1.

2.