Search code examples
c#asp.netdownloadresponse

How to download .txt file from a url?


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

    }
}

Solution

  • After sw.Close(); just Response.Redirect() them to the URL of the text file. You have to get the URL though, not the path on your physical hard drive. Based on your code you can do the following:

    Uri appRootUri = new Uri(HttpContext.Current.Request.ApplicationPath);
    Uri fileUri = new Uri(Path.GetFullPath(strFilePath));
    
    Uri relativeUri = fileUri.MakeRelativeUri(appRootUri);
    
    Response.Redirect("~/" + relativeUri.ToString());
    

    As suggested by aquinas in the comments, you should really be going the other way though. You should know the relative path to where you want to store the file, in which case you can do it this way instead:

    // If you want to store it at http://yourapplication/files/file.txt
    string relativeFilePath = "/files/file.txt";
    
    CreateCSVFile(dt, Server.MapPath(relativeFilePath));
    Response.Redirect("~" + relativeFilePath);