我正在使用下面的代码将大文件上传到服务器,并注意到将FileStream复制到GetRequestStream的字节数组已创建并保存在内存中。这增加了大对象堆,我不想要它。也许有人知道如何解决这个问题?

Stream formData = new FileStream(.....)

    HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
    using (Stream requestStream = request.GetRequestStream())
    {
     Helpers.CopyStream(formData, requestStream);
     requestStream.Close();
    }

     public static void CopyStream(Stream fromStream, Stream toStream)
            {
                try
                {
                    int bytesRead;
                    byte[] buffer = new byte[32768];
                    while (fromStream != null && (bytesRead = fromStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        toStream.Write(buffer, 0, bytesRead);
                    }
                }
                catch (IOException)
                {
                    //suppress empty stream response
                }
            }


内存分析器图。在GetRequestStream内部创建的bytes数组

最佳答案

您可以使用HttpWebRequest.AllowWriteStreamBuffering禁用内部缓冲:

    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

    request.AllowWriteStreamBuffering = false;

    using (Stream formData = File.Open(fileName, FileMode.Open))
    using (Stream requestStream = request.GetRequestStream())
    {
        formData.CopyTo(requestStream, 32768);
    }

09-25 17:00