我正在使用 RestSharp 实现一个简单的文件上传桌面工具。当我使用自定义流编写器将大文件添加到请求中(以将上传进度更新到 gui)时,stream.Write
会引发 OutOfMemoryException。简化代码示例:
...
var request = new RestRequest { Resource = "/test" };
request.Method = Method.POST;
request.AddFile("file", writer, "largefile.iso");
var response = client.Execute(request);
...
private void writer(Stream stream)
{
using (FileStream reader = File.OpenRead("d:\\download\\largefile.iso"))
{
byte[] buffer = new byte[16384]; //16k buffer
int bytesRead = 0;
int read = 0;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, read);
bytesRead += read;
System.Diagnostics.Debug.WriteLine("uploading: " + (int) ((double)bytesRead / reader.Length * 100) + "%");
}
reader.Close();
}
}
这适用于小文件,但流写入会泄漏内存,最终崩溃。有什么我在这里想念的吗?