How to download .txt file from a url?

Posted by Colin Roe on Stack Overflow See other posts from Stack Overflow or by Colin Roe
Published on 2012-10-19T12:40:47Z Indexed on 2012/10/19 17:01 UTC
Read the original article Hit count: 333

Filed under:
|
|
|

I produced a text file and is saved to a location in the project folder. How do I redirect them to the url that contains that text file, so they can download the text file.

CreateCSVFile creates the csv file to a file path based on a datatable.

Calling:

string pth = ("C:\\Work\\PG\\AI Handheld Website\\AI Handheld Website\\Reports\\Files\\report.txt");
CreateCSVFile(data, pth); 

And the function:

public void CreateCSVFile(DataTable dt, string strFilePath)
{

    StreamWriter sw = new StreamWriter(strFilePath, false);
    int iColCount = dt.Columns.Count;

    for (int i = 0; i < iColCount; i++)
    {
        sw.Write(dt.Columns[i]);

        if (i < iColCount - 1)
        {
            sw.Write(",");
        }
    }

    sw.Write(sw.NewLine);
    // Now write all the rows.
    foreach (DataRow dr in dt.Rows)
    {
        for (int i = 0; i < iColCount; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                sw.Write(dr[i].ToString());
            }

            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
    }
    sw.Close();
    Response.WriteFile(strFilePath);
    FileInfo fileInfo = new FileInfo(strFilePath);

    if (fileInfo.Exists)
    {
        //Response.Clear();
        //Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
        //Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        //Response.ContentType = "application/octet-stream";
        //Response.Flush();
        //Response.TransmitFile(fileInfo.FullName);

    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET