c# - 发送文件到客户端并删除

标签 c# asp.net download

我的服务器中有一个Word文档,我想发送给我的客户。实际上,我希望他们下载该文件。我正在运行时创建该文件,当他们从我的服务器下载该文件后,我想将其删除。我正在本地尝试这种情况。创建文件后,我的服务器将其发送给客户端。在网络浏览器中,我看到以下内容:



我不要这个我希望Web浏览器打开“保存文件”对话框。我希望客户端下载真实文件。这是我的代码:

           Guid temp = Guid.NewGuid();
           string resultFilePath = Server.MapPath("~/formats/sonuc_" + temp.ToString()  + ".doc");
            if (CreateWordDocument(formatPath, resultFilePath , theLst)) {

                Response.TransmitFile(resultFilePath);

                Response.Flush();

                System.IO.File.Delete(resultFilePath);

                Response.End();
            }

最佳答案

该代码段应该可以解决问题,但是请注意,这将导致将整个文件加载到(服务器的)内存中。

private static void DownloadFile(string path)
{
    FileInfo file = new FileInfo(path);
    byte[] fileConent = File.ReadAllBytes(path);

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", file.Name));
    HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.BinaryWrite(fileConent);
    file.Delete();
    HttpContext.Current.Response.End();
}

关于c# - 发送文件到客户端并删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778178/

相关文章:

javascript - 如何使用casperjs下载与我在浏览器中看到的页面相同的页面

c# - A* 3D 寻路 - Unity

C# 如何创建 while 循环来验证对象是否为 null

c# - 如何导入文件名为 "improper"的 CSV 文件?

c# - 在已部署的 Web 应用程序中出现编译错误,但在 IDE 中却没有出现编译错误

python - 如何编写用于下载的python脚本?

c# - 使用 C# 从 IntPtr 复制带有 Marshal.Copy 的字节数组不起作用

asp.net - 在 Javascript 中从对象数组创建 HTML 表

c# - 使用 C# 的 Google Analytics API

asp.net-mvc - MVC Controller.File 返回空白 pdf