public static FileInfo ToFileInfo(Stream stream, string fileName)
 {
     return(new FileInfo(fileName, StreamHelper.ReadAsBytes(stream)));
 }
        private WebRequest PrepareRequest(string path, string method, Dictionary <string, object> formParams,
                                          Dictionary <string, string> headerParams, string body, string contentType)
        {
            var request = WebRequest.Create(path);

            request.Method = method;

            byte[] formData = null;
            if (formParams.Count > 0)
            {
                var formDataBoundary = Guid.NewGuid().ToString();
                request.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
                formData            = GetMultipartFormData(formParams, formDataBoundary);

                request.ContentLength = formData.Length;
            }
            else
            {
                request.ContentType = contentType;
            }

            foreach (KeyValuePair <string, string> headerParamsItem in headerParams)
            {
                request.Headers.Add(headerParamsItem.Key, headerParamsItem.Value);
            }

            foreach (KeyValuePair <string, string> defaultHeaderMapItem in _defaultHeaderMap)
            {
                if (!headerParams.ContainsKey(defaultHeaderMapItem.Key))
                {
                    request.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value);
                }
            }

            MemoryStream streamToSend = null;

            try
            {
                switch (method)
                {
                case "GET":
                    break;

                case "POST":
                case "PUT":
                case "DELETE":
                    streamToSend = new MemoryStream();

                    if (formData != null)
                    {
                        streamToSend.Write(formData, 0, formData.Length);
                    }

                    if (body != null)
                    {
                        var requestWriter = new StreamWriter(streamToSend);
                        requestWriter.Write(body);
                        requestWriter.Flush();
                    }

                    break;

                default:
                    throw new ApiException(500, "unknown method type " + method);
                }

                _requestHandlers.ForEach(p => p.BeforeSend(request, streamToSend));

                if (streamToSend != null)
                {
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        StreamHelper.CopyTo(streamToSend, requestStream);
                    }
                }
            }
            finally
            {
                streamToSend?.Dispose();
            }

            return(request);
        }