How to download .txt file from a url?
- by Colin Roe
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);
}
}