How to Create a text file in ASP .NET ? |
Written on: May, 13th 2002. |
Introduction
One of the frequent task in any web application is dealing with the text files. In classic ASP, we used the FileSystemObject to deal with files. In this article, we will see how to create text files in ASP .NET.
Things that we will be learning in this article
- The namespace that is required to deal with Files
- The StreamWriter Object
- Creating a Text File
- How to capture errors which may occur while creating a text file?
The Namespace that is required to deal with Files
We require the namespace, System.IO to work with files. So, we should import this namespace in our ASPX page such as
<%@ Import Namespace="System.IO" %>
How to Create a text File?
To start with, we need to create an instance of the object, StreamWriter. The instance will be the file pointer for us. Once we have a File Pointer, we need to invoke the method, CreateText method of the object, File. The method, CreateText takes a string as an argument. The string is nothing but the path of file that is going to get created. Now, let us see an example. Let us assume, we have a textbox with textmode set to MultiLine and a button. On the click event of the button, we need to create a text file. The code within the Click event is shown below.
Code in the OnClick event of button.
Sub WriteToFile(sender As Object, e As EventArgs)
Dim fp As StreamWriter
Try fp = File.CreateText(Server.MapPath(".\Upload\") & "test.txt") fp.WriteLine(txtMyFile.Text) lblStatus.Text = "File Succesfully created!" fp.Close() Catch err As Exception lblStatus.Text = "File Creation failed. Reason is as follows
" & err.ToString() Finally
End Try
End Sub |
How it works?
We are first creating an instance of StreamWriter, which is termed as fp (file pointer). Then, in the Try block, we invoke the CreateText method. To write the content, we use the method, WriteLine. Actually, we have just three lines of code which writes data to a text file. Once we have successfully written to the text file, we close the StreamWriter by invoking the Close method of StreamWriter.
Sample output of our scenario
Fig: Creating Text Files in ASP .NET
Test this Script
Download the code
Click here to download the ASPX page
Conclusion
Creating a text file is very easy. We can easily create a text file in just 3 lines of code. To read content from a text file, visit my article Read data from Text File
Links
Textbox Web Server Control
Reading data from a Text File
Send your comments to das@aspalliance.com