Create a text file in ASP.NET

We need the namespace, System.IO to use files.

The method, CreateText requires a string for an argument. The string is the path of file which will be created. After we have correctly written to the text file, we close the StreamWriter by invoking the Close method of StreamWriter. See below for example code.

<!DOCTYPE html>

<script runat="server">

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim TextFile As New System.IO.StreamWriter(Server.MapPath("test.txt"))
        TextFile.WriteLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
        TextFile.Close()
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>
Updated: March 6, 2015 — 5:00 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Charon © 2015 Privacy Policy | Terms & Conditions Frontier Theme