1
ImageFile currImage = (ImageFile)image;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(BuildUrl(currImage.Meta));
req.AllowWriteStreamBuffering = false;
req.Method = "POST";                                
req.ContentType = currImage.MimeType;
req.ContentLength = currImage.Meta.Length;

var fileStream = new FileStream(
                    currImage.Meta.FullName,
                    FileMode.Open,
                    FileAccess.Read, // Allows share file with other processes !important
                    FileShare.Read
                );

// Prepare to read the file and push it into request stream
using (BinaryReader fileReader = new BinaryReader(fileStream))
{
    using (Stream requestStream = req.GetRequestStream())
    {
        // Create a buffer for image data
        const int bufSize = 1024;
        byte[] buffer = new byte[bufSize];
        int chunkLength = 0;

        // Transfer data
        while ((chunkLength = fileReader.Read(buffer, 0, bufSize)) > 0)
        {
            IAsyncResult result = requestStream.BeginWrite(buffer, 0, chunkLength, null, null);

            // Check for cancellation here <-----
            if (token.IsCancellationRequested)
            {                               
                _logger.Info(String.Format("Uploading {0} was cancelled in process.", currImage.Meta.FullName));                                
                token.ThrowIfCancellationRequested();
            }

            result.AsyncWaitHandle.WaitOne();
            requestStream.EndWrite(result);
        }
    }
}

try
{
    // Read image ID from the response
    WebResponse response = req.GetResponse();
    TextReader responseReader = new StreamReader(response.GetResponseStream());

    string imageId = responseReader.ReadToEnd();

    long id;
    if (String.IsNullOrEmpty(imageId) && !Int64.TryParse(imageId, out id))
        throw new Exception("Wrong response for an uploaded image");
}
catch (Exception exp)
{
    _logger.Error(String.Format("Unable to read ImageId answer: {0}", exp.ToString()));                 
}

我正在使用此代码将文件上传到我的服务器,但如果出现取消情况,如果在上传过程中出现取消,我会收到错误消息。

System.Net.WebException:请求被中止:请求被取消。---> System.IO.IOException:在写入所有字节之前无法关闭流。在 System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting) --- 内部异常堆栈跟踪结束 --- 在 System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting) 在 System.Net.ConnectStream.System .Net.ICloseEx.CloseEx(CloseExState closeState) at System.Net.ConnectStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose()

我怎样才能正确管理它?我试图在 token.ThrowIfCancellationRequested(); 之前手动调用 req.Abort() 或 requestStream.Close()

我明白为什么会出现这个错误,但我不知道该怎么说系统没问题 - 我想断开连接。

4

0 回答 0