OutOfMemoryException with RestSharp 文件上传

本文关键字:文件 RestSharp with OutOfMemoryException | 更新日期: 2023-09-27 18:31:42

我正在使用RestSharp实现一个简单的文件上传桌面工具。当我使用自定义流编写器将大文件添加到请求中时(以将上传进度更新到 gui),stream.Write抛出内存异常。简化的代码示例:

...
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();
    }
}

这适用于小文件,但流写入会泄漏内存,最终崩溃。我在这里缺少什么吗?

OutOfMemoryException with RestSharp 文件上传

也许您应该尝试在每次写入后刷新流缓冲区:

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);
                stream.Flush();
                bytesRead += read;
                System.Diagnostics.Debug.WriteLine("uploading: " + (int)((double)bytesRead / reader.Length * 100) + "%");
            }
            reader.Close();
        }
    }

在挖掘 RestSharp 源代码后自己解决了这个问题。 http://support.microsoft.com/kb/908573