0

我正在使用 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();
    }

}

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

4

2 回答 2

0

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

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

    }
于 2012-04-18T13:50:12.920 回答
0

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

于 2012-04-19T18:03:05.440 回答