Monday, February 25, 2013

Writing to a Text File (C#)

 

To perform file operations , use the namespace “using System.IO” .  StreamWriter class provides functions to write data to file and Stream Reader class provides functions to read data from file and to append data if required.

Sample code to write data to a Text File :

Aspx Code :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SaveTextToFile.aspx.cs" Inherits="Santhakam_SaveTextToFile" %>

<!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 FILE</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr>
            <td>
                Enter Text:
            </td>
            <td>
                <asp:TextBox ID="txtMsg" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnWriteTextToFile" runat="server" Text ="WriteTextToFile"  OnClick="btnWriteTextToFile_Click" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Label ID="lblMsg" runat="server" Font-Bold="True" 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 Santhakam_SaveTextToFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void WritetoTextFile()
    {
        //CREATE OBJECT FOR STREAMWRITER CLASS
        StreamWriter obj;
        try
        {
            /*CREATE TEXT FILE*/
            obj = File.CreateText("C:\\Sample.txt");
            /*WRITE DATA TO FILE*/
            obj.WriteLine(txtMsg.Text);
            obj.Flush();
            obj.Close();           
        }
        catch (Exception ex)
        {
            //ErrorPage.ToString();
        }

    }
   protected void btnWriteTextToFile_Click(object sender, EventArgs e)
    {
        WritetoTextFile();
        lblMsg.Text = "File has been created and text is saved to file Successfully";
    }
}

Output :

SaveTexttofile1      Savetexttofile2

No comments:

Post a Comment