-1

我生成了一个文本文件并保存到项目文件夹中的某个位置。如何将它们重定向到包含该文本文件的 url,以便他们可以下载文本文件。

CreateCSVFile 将 csv 文件创建到基于数据表的文件路径。

来电:

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

和功能:

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

    }
}
4

2 回答 2

1

之后sw.Close();只是Response.Redirect()他们到文本文件的 URL。但是,您必须获取 URL,而不是物理硬盘驱动器上的路径。根据您的代码,您可以执行以下操作:

Uri appRootUri = new Uri(HttpContext.Current.Request.ApplicationPath);
Uri fileUri = new Uri(Path.GetFullPath(strFilePath));

Uri relativeUri = fileUri.MakeRelativeUri(appRootUri);

Response.Redirect("~/" + relativeUri.ToString());

正如阿奎那在评论中所建议的那样,你真的应该走另一条路。您应该知道要存储文件的位置的相对路径,在这种情况下,您可以这样做:

// 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);
于 2012-10-19T12:59:40.067 回答
1

Response.Redirect("~/Reports/Files/report.txt");

于 2012-10-19T12:52:22.377 回答