- How to create text file and write text programmatically

Create a text file and write text programmatically
the following c# example code demonstrate us how can we create a text file and write text on it programmatically in .net framework.

we can get the application physical path using HttpRequest.PhysicalApplicationPath property as Request.PhysicalApplicationPath. we also can get the file path by adding two strings, those are physical application path and file name with extension. in this example we created a text file name Text.txt and programmatically write two line of text in this file at run time.

StreamWriter Class allow us to implement a TextWriter for writing characters to a stream in a particular encoding. in this example code we initialize a StreamWriter object.

File.CreateText(path) method create or open a file for writing UTF-8 encoded text. this method require to pass a parameter name 'path'. path parameter value specify the file to be opened for writing. this method return value type is System.IO.StreamWriter.

StreamWriter WriteLine(String) method allow us to write a string followed by a line terminator to the text string or stream.

StreamWriter Flush() method clears all buffer for the current writer and causes any buffered data to be written to the underlying stream.

StreamWriter Close() method closes the current StreamWriter object and the underlying stream.

in an page we need to include System.IO namespace before working with files and directories.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, System.EventArgs e)
        string appPath = Request.PhysicalApplicationPath;
        string filePath = appPath + "Text.txt";
        StreamWriter w;
        w = File.CreateText(filePath);
        w.WriteLine("This is a test line.");
        w.WriteLine("This is another line.");
        Label1.Text = "File created and write successfully!<br />";
        Label1.Text += filePath;

<html xmlns="">
<head id="Head1" runat="server">
    <title>How to create text file and write text programmatically in</title>
    <form id="form1" runat="server">
        <h2 style="color:Red"> StreamWriter example:<br />Create File and Write In It</h2>
        <br /><br />
             Text="Create File and Write Text"

More examples