代码之家  ›  专栏  ›  技术社区  ›  Bhanu Gotluru

如何删除作为HttpResponseMessage的StreamContent发送的文件

  •  20
  • Bhanu Gotluru  · 技术社区  · 13 年前

    在ASP.NET webapi中,我向客户端发送一个临时文件。我打开一个流来读取文件,并在HttpResponseMessage上使用StreamContent。一旦客户端收到文件,我想删除这个临时文件(不需要客户端的任何其他调用) 一旦客户端接收到该文件,就会调用HttpResponseMessage的Dispose方法&流也被处理掉。现在,我也想在这一点上删除临时文件。

    一种方法是从HttpResponseMessage类派生一个类,重写Dispose方法,删除这个文件&调用基类的dispose方法。(我还没有尝试过,所以不知道这是否有效)

    我想知道是否有更好的方法来实现这一点。

    3 回复  |  直到 12 年前
        1
  •  15
  •   Community Mohan Dere    9 年前

    事实上 your comment 帮助解决了这个问题。。。我在这里写到:

    Delete temporary file sent through a StreamContent in ASP.NET Web API HttpResponseMessage

    这是对我有效的方法。注意里面的呼叫顺序 Dispose 与您的评论不同:

    public class FileHttpResponseMessage : HttpResponseMessage
    {
        private string filePath;
    
        public FileHttpResponseMessage(string filePath)
        {
            this.filePath = filePath;
        }
    
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
    
            Content.Dispose();
    
            File.Delete(filePath);
        }
    }
    
        2
  •  15
  •   SergeyS    9 年前

    从具有DeleteOnClose选项的FileStream创建StreamContent。

    return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StreamContent(
            new FileStream("myFile.txt", FileMode.Open, 
                  FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose)
        )
    };
    
        3
  •  4
  •   UnionP    11 年前

    我首先将文件读取到字节[]中,删除文件,然后返回响应:

            // Read the file into a byte[] so we can delete it before responding
            byte[] bytes;
            using (var stream = new FileStream(path, FileMode.Open))
            {
                bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);
            }
            File.Delete(path);
    
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(bytes);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.Add("content-disposition", "attachment; filename=foo.bar");
            return result;
    
    推荐文章