我正在尝试创建一种方法,在用户下载时不断传输zip文件(这样就不会浪费流媒体)
我添加了一个thread.sleep来模拟延迟
public override void ExecuteResult(ControllerContext context) {
HttpResponseBase response = context.HttpContext.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Cookies.Clear();
response.ContentType = ContentType;
response.ContentEncoding = Encoding.Default;
response.AddHeader("Content-Type", ContentType);
context.HttpContext.Response.AddHeader("Content-Disposition",
String.Format("attachment; filename={0}",
this.DownloadName));
int ind = 0;
using (ZipOutputStream zipOStream =
new ZipOutputStream(context.HttpContext.Response.OutputStream))
{
foreach (var file in FilesToZip)
{
ZipEntry entry = new ZipEntry(FilesToZipNames[ind++]);
zipOStream.PutNextEntry(entry);
Thread.Sleep(1000);
zipOStream.Write(file, 0, file.Length);
zipOStream.Flush();
}
zipOStream.Finish();
}
response.OutputStream.Flush();
}
Run Code Online (Sandbox Code Playgroud)
看起来拉链将不会开始流式传输,直到所有文件都是压缩文件.有没有办法连续流?也许有一个不同的图书馆?
我在C#MVC应用程序中有一个函数,它创建一个临时目录和一个临时文件,然后使用FileStream打开文件,将FileStream返回给调用函数,然后需要删除临时文件.但是,我不知道如何删除临时目录和文件,因为它总是错误地说"进程无法访问该文件,因为它正被另一个进程使用".这是我尝试过的,但FileStream仍在使用finally块中的临时文件.如何返回FileStream并删除临时文件?
public FileStream DownloadProjectsZipFileStream()
{
Directory.CreateDirectory(_tempDirectory);
// temporary file is created here
_zipFile.Save(_tempDirectory + _tempFileName);
try
{
FileStream stream = new FileStream(_tempDirectory + _tempFileName, FileMode.Open);
return stream;
}
finally
{
File.Delete(_tempDirectory + _tempFileName);
Directory.Delete(_tempDirectory);
}
}
Run Code Online (Sandbox Code Playgroud)
FileStream返回的函数如下所示:
public ActionResult DownloadProjects ()
{
ProjectDownloader projectDownloader = new ProjectDownloader();
FileStream stream = projectDownloader.DownloadProjectsZipFileStream();
return File(stream, "application/zip", "Projects.zip");
}
Run Code Online (Sandbox Code Playgroud)
更新:我忘了提到zip文件是380 MB.使用MemoryStream时,我遇到了系统内存不足的问题.