我使用下面的代码将大文件上传到服务器,并注意到将FileStream复制到GetRequestStream,创建了bytes数组并保存在内存中。这增加了大对象堆,我不想要它。也许有人知道如何解决这个问题?
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
}
}
内存分析器图。 bytes数组在GetRequestStream内部创建
答案 0 :(得分:2)
您可以使用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);
}