C#为什么上传大文件时出现内存不足异常?

时间:2018-12-07 14:41:07

标签: c#

我正在将一个大文件读入流,其中正在填充要写入HttpWebRequest流的4k缓冲区。

由于某种原因,我无法使用内存异常,不知道为什么。

我做错了什么吗?

我的方法:

public void StreamBlob(FileInfo file, Uri blobContainerSasUri, string containerName)
{
    try
    {
        var method = "PUT";
        var token = blobContainerSasUri.Query;
        var requestUri =
            new Uri($"https://{blobContainerSasUri.Host}/{containerName}/{string.Concat(file.Name, token)}");

        using (var fileStream = file.OpenRead())
        {
            var request = (HttpWebRequest) WebRequest.Create(requestUri);
            request.Method = method;
            request.ContentType = MimeMapping.GetMimeMapping(file.FullName);
            request.Headers.Add("x-ms-blob-type", "BlockBlob");
            request.ContentLength = fileStream.Length;
            request.AllowWriteStreamBuffering = false;

            using (var serverStream = request.GetRequestStream())
            {
                var buffer = new byte[4096];
                while (true)
                {
                    var bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead > 0)
                        serverStream.Write(buffer, 0, bytesRead);
                    else
                        break;
                }
            }

            using (var resp = (HttpWebResponse) request.GetResponse())
            {
                try
                {
                    if (resp.StatusCode == HttpStatusCode.OK)
                        _logger.Log.Info("Received http response {resp}");
                }

                catch (Exception ex)
                {
                    _logger.Log.Warn($"Received http response {resp}", ex)
                }
            }
        }
    }
    catch (Exception ex)
    {
        _logger.Log.Warn($"Error uploading {file.Fullname}, ex")
    }

0 个答案:

没有答案