- , , TimeOut, .
HttpClient. , Thomas Levesque . HttpWebRequest HttpClient. - ,
FileStream , (upload). , .
TL. , !:
long UploadFile(string path, string url, string contentType)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
request.AllowWriteStreamBuffering = false;
request.ContentType = contentType;
string fileName = Path.GetFileName(path);
request.Headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", fileName);
try
{
using (var fileStream = File.OpenRead(path))
{
request.ContentLength = fileStream.Length;
using (var requestStream = request.GetRequestStreamWithTimeout())
{
fileStream.CopyTo(requestStream);
}
}
using (var response = request.GetResponseWithTimeout())
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
string json = reader.ReadToEnd();
var j = JObject.Parse(json);
return j.Value<long>("Id");
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.Timeout)
{
LogError(ex, "Timeout while uploading '{0}'", fileName);
}
else
{
LogError(ex, "Error while uploading '{0}'", fileName);
}
throw;
}
}