How to Create a text file in ASP .NET ?
page 1 of 1
Published: 22 Oct 2003
Unedited - Community Contributed
Abstract
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.
by Jesudas Chinnathampi (Das)
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 37385/ 21

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
  1. The namespace that is required to deal with Files
  2. The StreamWriter Object
  3. Creating a Text File
  4. 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

Creating Text Files in ASP .NET - 15,605  bytes
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       



User Comments

Title: sds   
Name: dsd
Date: 2012-12-10 7:31:26 AM
Comment:
sadsadsadsaddds
Title: hi!   
Name: Rashid Jabbar
Date: 2012-12-06 12:39:46 AM
Comment:
thank u very much but i want C# code for that :(
Title: BOO   
Name: jon
Date: 2012-11-04 10:35:03 AM
Comment:
I ask for C# and got VB
Title: sdasda   
Name: asdad
Date: 2012-11-02 8:11:48 AM
Comment:
sdadadadadadadadaddad
Title: Hello   
Name: Ba
Date: 2012-08-06 9:33:05 AM
Comment:
Wow
Title: understanding ASP.net   
Name: leadlight
Date: 2011-12-20 1:50:12 AM
Comment:
At first I was really confused in understanding ASP.net. Tags are really confusing.. Isn’t it? Anyways, as far as I know, service controls are tags basically an HTML tags understood by servers. Server control must always be properly executed so that you will not have a problem in your codes.
Title: File creation   
Name: sanjay gupta
Date: 2011-07-10 6:59:31 AM
Comment:
very good and easy to understand
Title: Good Article   
Name: M.Usman
Date: 2011-05-02 8:32:30 AM
Comment:
It's really a good article for the beginner.
Title: HELP Please - Brand New to ASP.Net   
Name: Sam
Date: 2011-03-08 9:39:59 PM
Comment:
I am just starting to learn asp.net and my first task is to create a new project that reads data from an SQL 2005 DB and creates a text file to be saved to a server using the info in the db. As a basis for my program I was using a program that creates emails and sends them. However this program just uses the program.cs file. I am not sure what type of program i need to add to be able to have the aspx page? Thanks
Title: Nice   
Name: Nidhya
Date: 2010-10-27 2:40:36 AM
Comment:
Its Very Use full For me
Title: Append   
Name: lois
Date: 2010-10-23 5:08:16 AM
Comment:
I want to append text in my text file.
Title: Brilliant.. No fuss and hard to understand code   
Name: Andy
Date: 2010-10-02 8:05:14 AM
Comment:
Fantastic. Code worked out of the text box :-) No click here for this, or add this to get that, pure and simple, working pages. All I wanted to do was create a text file on my server, and this code did that very simply. Well done.
Title: Need ur HELP   
Name: Priya
Date: 2010-08-30 2:50:13 AM
Comment:
Please advise if we can use same code for ASp.net 2008 using C# .
AS I tried this code but it is not working ..

I am not able to capture the file path in the FileInfo object reference...
Title: Still not working. .   
Name: Priya
Date: 2010-08-30 2:48:41 AM
Comment:
Still not working. .
Title: asp   
Name: jyothsna
Date: 2010-08-07 7:02:34 AM
Comment:
its nice beginers i'll learn, i learn thank 'u'.
Title: C#   
Name: FAIZA
Date: 2010-07-25 12:15:37 PM
Comment:
Can you write the above code in C# as well? :) thanx !
Title: gud work   
Name: riddhi
Date: 2010-04-21 6:11:21 AM
Comment:
thank you very much......

it was very useful!!!!!!!!!
Title: tan x   
Name: Mano
Date: 2010-03-25 6:41:07 AM
Comment:
very usefull... tanx
Title: Reading some text from one file and then writing it to another file with different name   
Name: Varun Sareen
Date: 2010-01-19 5:20:02 AM
Comment:
My problem is as follows:

In ASP.Net1.1, I have created an xml static file(temp) and saved it to the project folder. Now i want to read the data from the TEMP file and then write it upon the new file created with different name. But i am getting the error when i am deleting the new file that ("The process cannot access the file because it is being used by another process in asp.net") in order to update it from the saved static xml file(temp). I am adding my code also for ref.

string site_map="";
string site_map_new="";
private void Page_Load(object sender, System.EventArgs e) {
// site_map=Server.MapPath("site_map_static");
site_map=Server.MapPath("site_map_static.xml");
site_map_new=Server.MapPath("site_map.xml");
FileInfo fileInfo=new FileInfo(site_map);
FileStream fileRead=new FileStream(fileInfo.ToString(),FileMode.Open,FileAccess.Read);
fileRead= fileInfo.OpenRead();
StreamReader sr_new =new StreamReader(fileRead);
sr_new.ReadToEnd().ToString();
sr_new.Close();
fileRead.Close();

FileInfo fileInfoNew=new FileInfo(site_map_new);
if(fileInfoNew.Exists) {
fileInfoNew.Delete();
fileInfoNew.Create();
}
else {
fileInfoNew.Create();
}
bool _Open=true;
FileStream fw =null;
while(_Open)
{
try{
fw = new FileStream(fileInfoNew.ToString(),FileMode.Open,FileAccess.Write,FileShare.None);
fw.Close();
fw.Flush();
break;}
catch(Exception ex) {
Response.Write(ex.Message.ToString());
}
}
FileStream fileWrite = fileInfoNew.OpenWrite();
StreamWriter sw= new StreamWriter(fileWrite);
sw.Write(sr_new.ToString());
sw.Flush();
sw.Close();

StreamReader sr=new StreamReader(fileInfoNew.OpenRead());
while(sr.Peek()!=-1)
Response.Write(sr.ReadToEnd().ToString());
}
Title: Server. mappath   
Name: hex
Date: 2009-11-12 11:33:10 AM
Comment:
Thanx!!! The Server.mapPath method was exactly what i was missing
Title: Nice Article   
Name: Amit Gupta
Date: 2009-08-24 6:36:21 AM
Comment:
It is really a short and clear article, thanks
Title: thankx a lot   
Name: sagar
Date: 2009-05-21 1:22:28 PM
Comment:
very useful article ... thanks a lot...
Title: Ing   
Name: Marlon Cantillo
Date: 2008-11-04 4:43:09 PM
Comment:
The example is very single. Short and very helpful...

Thanx a lot.
Title: thank   
Name: reefaq
Date: 2008-10-18 3:59:25 AM
Comment:
Thanks man its really very use full to me
Title: Thank you for the precious article.   
Name: Sumit
Date: 2008-10-13 6:33:58 AM
Comment:
Thank you for the precious article........
Title: hi....   
Name: anuj panwar
Date: 2008-08-09 7:09:55 AM
Comment:
hello to all.
Title: very-2 useful and easy to learn article.   
Name: Sachin Dev Tripathi
Date: 2008-08-07 6:18:16 AM
Comment:
This article is very important for me.bcz i want 2 make a on the fly html file,but i got so errors with filestream object till now..i was confused that what 2 do.at this condition..thx 4 this article.
Title: Excellent Articles   
Name: Mohammad Javed
Date: 2008-07-11 7:55:21 AM
Comment:
Article address's what I want but with my limited knowledge I am lost. Have a excel workbook that I create to sheets in these are maile & maild. I want to be able to take data from these sheets to a text file for mail merge use. Word mail merge searches entire excel sheet this takes to long. Have never done this before. Thanks
Title: very useful   
Name: Sals
Date: 2008-05-21 4:56:52 AM
Comment:
I got very useful. This simple example explains lot. Tnx
Title: good   
Name: Balas
Date: 2008-05-21 4:54:46 AM
Comment:
Good...Tnx a lot
Title: Pro Bono producer   
Name: Curt cagreer@att.net
Date: 2008-04-18 1:36:48 PM
Comment:
Article address's what I want but with my limited knowledge I am lost. Have a excel workbook that I create to sheets in these are maile & maild. I want to be able to take data from these sheets to a text file for mail merge use. Word mail merge searches entire excel sheet this takes to long. Have never done this before. Thanks
Title: Here is C# code of this article   
Name: isozworld (Ismail OZER)
Date: 2008-03-12 6:05:54 PM
Comment:
\
\
Title: It is realy clear.   
Name: isozworld (Ismail ÖZER)
Date: 2008-03-12 6:03:28 PM
Comment:
hi,
thank you very much for your clear and easy to understand work.
Title: how to create .aspx ?   
Name: KCJ
Date: 2007-12-26 7:18:33 AM
Comment:
Hai
how to create .aspx file from master pages... means dynamicaly i want to create content pages from ther master pages...
is it possible..
plz mail me "kcjagadeep at yahoo.com"
Title: hi   
Name: ray
Date: 2007-12-16 10:30:07 AM
Comment:
how about c#?
Title: Real Cool   
Name: Lennie
Date: 2007-11-21 1:54:35 PM
Comment:
This article is so practical and so easy to understand. Thank you very much for sharing your experiences and knowledges with us.
Title: :)   
Name: RED
Date: 2007-11-11 6:36:09 AM
Comment:
Very Helpfull
Tx a lot
Title: TY   
Name: PotHead
Date: 2007-08-24 1:58:26 AM
Comment:
Ty 4 this source...it works
Title: Hello   
Name: Dip
Date: 2007-08-23 4:42:25 AM
Comment:
It helped me a lot!
Title: Creating folder at client's machine using ASP.NET   
Name: RAHUL KATE
Date: 2007-07-31 6:20:24 AM
Comment:
Hi,
I want to create a Folder and an Excel Sheet on the Client's PC using ASP.NET WebForms. Any Idea is it possible using C#?

Any Help Greatly Appreciated.
Regards,
Rahul
Title: good article helps it lot   
Name: Dastagiri
Date: 2007-05-21 2:29:57 AM
Comment:
this is very helpfull and keep help people as you know that you will get more complements knowledge
Title: how to create text file on client side's C:\   
Name: b.s.srinu
Date: 2007-01-11 4:15:47 AM
Comment:
plz anyone know tell me how to create a client side file.

I want to create a text file on each client machines and access it for printing.

Printing I solved, now problem is of creation of files on client machine
Title: Great Article!   
Name: John Dunlap
Date: 2006-11-19 9:23:03 PM
Comment:
Great article - very easy to understand, and very practical. Good Job! :)
Title: How to Create a text file in ASP .NET ?   
Name: ashita
Date: 2006-09-04 3:00:21 AM
Comment:
It is realy a good article which has solved my problem.
Title: how to create a text file   
Name: Ramesh
Date: 2006-08-14 6:50:20 AM
Comment:
it's goood
Title: Permission   
Name: AF
Date: 2006-06-08 11:23:27 AM
Comment:
What about permissions ?
I have some problems when I create the text file (System.Security.Permissions.FileIOPermission)
Title: to create save multiple file on single clik   
Name: swati
Date: 2006-06-03 5:35:36 AM
Comment:
hi i want to download a single file and image files linked to that file how can i do it
Title: To create no. of files in a single folder   
Name: BKDas
Date: 2006-05-29 1:56:52 AM
Comment:
I want to create multiple files by selecting files through browse option in a single folder.Can u help me?
Title: How to open a notepad application using asp.net code   
Name: Arun Kumar.P
Date: 2006-05-24 12:12:43 PM
Comment:
This is an excellent example to create a text file. Could you explain how to open a notepad application file using asp.net.
Title: how to create text file on client side's C:\   
Name: sunil
Date: 2006-03-25 6:13:46 AM
Comment:
plz anyone know tell me how to create a client side file.

I want to create a text file on each client machines and access it for printing.

Printing I solved, now problem is of creation of files on client machine.
Title: Concept is good   
Name: Amit
Date: 2006-02-22 4:28:31 PM
Comment:
Good article send more articles
Title: How to Create a text file in ASP .NET ?   
Name: Meghana
Date: 2005-10-21 2:14:26 AM
Comment:
Good one!!
Thanks....
Title: How to Create a text file in ASP .NET ?   
Name: Azlan
Date: 2005-10-21 12:06:13 AM
Comment:
Thanks!!!!!
Title: how do you get that file to the client   
Name: ed
Date: 2005-07-19 2:35:05 PM
Comment:
how would you send that file to the client because right now it is on the server and no good to anyone?????
Title: creating folder   
Name: prabhakar dwivedi
Date: 2005-05-31 10:11:06 AM
Comment:
can you give me the idea for creating folder in asp.net
Title: FP.Close()   
Name: Uh-oh!
Date: 2005-04-13 2:06:03 PM
Comment:
You should put the fp.Close() in the finally branch so the file gets closed if there was an error.
Title: How to Create a text file in ASP .NET ?   
Name: Don Sanders
Date: 2005-02-26 5:46:21 PM
Comment:
This was an excellent article that solved my problem completely.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 12:30:46 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search