下载.zip文件在c#.net
问题描述:
我试图从我的.net C#应用程序下载.zip文件。没有成功。我的代码如下。文件路径和名称是完全有效的,只是似乎没有下载。请注意,我如何将“应用程序/ x-zip压缩”和“应用程序/ zip”作为内容类型(一个注释掉,都尝试过)。两者都不起作用。没有任何错误的迹象,只是没有下载。下载.zip文件在c#.net
什么是坚果是我发誓这个代码在几个星期前工作,随着消息弹出,“另存为”选项被给出,只是因为任何原因现在不发生。
任何人看到任何错误,或者我的问题是否存在于代码之外的其他地方?
FileInfo file = new FileInfo(filepath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
//Response.ContentType = "application/x-zip-compressed";
Response.ContentType = "application/zip";
Response.WriteFile(file.FullName);
答
我猜你在Response.AddHeader("Content-Length", file.Length.ToString());
得到一个FileNotFoundException
。
若要解决此问题,您必须使用Server.MapPath(...)
,它将应用程序的根目录添加到filename
。 此外,您应该Flush()
和End()
您的Response
正确到force the client接收它。
string filename = "myfile.zip";
string serverpath = Server.MapPath($"~/{filename}");
FileInfo file = new FileInfo(serverpath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/zip";
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
那么......问题是什么?你在看什么?任何错误?它挂着吗? – JuanR