我制作了一个文本文件并保存到项目文件夹中的某个位置。 如何将它们重定向到包含该文本文件的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);
}
}
答案 0 :(得分:1)
的Response.Redirect( “〜/报告/文件/ REPORT.TXT”);
答案 1 :(得分:1)
将sw.Close();
Response.Redirect()
后只需Uri appRootUri = new Uri(HttpContext.Current.Request.ApplicationPath);
Uri fileUri = new Uri(Path.GetFullPath(strFilePath));
Uri relativeUri = fileUri.MakeRelativeUri(appRootUri);
Response.Redirect("~/" + relativeUri.ToString());
到文本文件的网址。您必须获取URL,而不是物理硬盘上的路径。根据您的代码,您可以执行以下操作:
// 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);
正如aquinas在评论中所建议的那样,你应该走另一条路。您应该知道存储文件的相对路径,在这种情况下,您可以这样做:
{{1}}