article

Download String as File

Email
Submitted on: 1/2/2015 8:48:00 AM
By: Mark M. Lanning (from psc cd)  
Level: Beginner
User Rating: By 4 Users
Compatibility: ASP.NET
Views: 673
 
     This may seem simple but I didn't find anything like this anywhere and I thought I should add it so it will help others. This artitle is to show you how to send a string variable as a downloadable file in asp.net.

 
				

To send a string variable to the client as a downloadable file you must first convert the string data over to a byte array... once in a byte array you can send the byte array to the client. Here is the code that will send a string as a file to the client:

Public Function SendFileToClient(ByRef WebPage As UI.Page, ByVal strFileData As String, ByVal strFileName As String) As Boolean

Try

'convert the passed file string to a byte array
Dim byteArray() As Byte = System.Text.Encoding.ASCII.GetBytes(strFileData)

'send the data to the client
WebPage.Response.Clear()
WebPage.Response.ContentType = "text/plain"
WebPage.Response.AddHeader("Content-Disposition", "attachment;filename=" & strFileName & ";")
WebPage.Response.BinaryWrite(byteArray)
WebPage.Response.End()

Catch ex As Exception

'trap the error and return false saying that something happened
Return False

End Try

'if success then return true
Return True

End Function

That is it.. just pass the function the string and the filename you want to be specified and bingo. So the function call would look something like this:

'send the file data to the client
Call SendFileToClient(Me, mExportData, "Export.csv")


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.