README.md

December 4, 2022 · View on GitHub

Download String as File

Description

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.

More Info

Submitted On
ByMark M. Lanning
LevelBeginner
User Rating5.0 (20 globes from 4 users)
CompatibilityASP.NET
CategoryFiles
World.Net (C#, VB.net)
Archive File

Source Code

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")