本文整理汇总了C#中ResponseStream.CopyTo方法的典型用法代码示例。如果您正苦于以下问题:C# ResponseStream.CopyTo方法的具体用法?C# ResponseStream.CopyTo怎么用?C# ResponseStream.CopyTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ResponseStream
的用法示例。
在下文中一共展示了ResponseStream.CopyTo方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveFile
public void SaveFile(string fileId, string downloadUrl)
{
Global.Logger.Debug("BoxApp: save file stream " + fileId + " from - " + downloadUrl);
fileId = ThirdPartySelector.GetFileId(fileId);
var token = Token.GetToken(AppAttr);
if (token == null)
{
Global.Logger.Error("BoxApp: token is null");
throw new SecurityException("Access token is null");
}
var boxFile = GetBoxFile(fileId, token);
if (boxFile == null)
{
Global.Logger.Error("BoxApp: file is null");
throw new Exception("File not found");
}
var jsonFile = JObject.Parse(boxFile);
var title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value<string>("name"));
var request = (HttpWebRequest)WebRequest.Create(BoxUrlUpload.Replace("{fileId}", fileId));
using (var tmpStream = new MemoryStream())
{
var boundary = DateTime.UtcNow.Ticks.ToString("x");
var metadata = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title);
var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata);
var bytes = Encoding.UTF8.GetBytes(metadataPart);
tmpStream.Write(bytes, 0, bytes.Length);
var downloadRequest = WebRequest.Create(downloadUrl);
using (var downloadResponse = downloadRequest.GetResponse())
using (var downloadStream = new ResponseStream(downloadResponse))
{
downloadStream.CopyTo(tmpStream);
}
var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary);
bytes = Encoding.UTF8.GetBytes(mediaPartEnd);
tmpStream.Write(bytes, 0, bytes.Length);
request.Method = "POST";
request.Headers.Add("Authorization", "Bearer " + token.AccessToken);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.ContentLength = tmpStream.Length;
Global.Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length);
const int bufferSize = 2048;
var buffer = new byte[bufferSize];
int readed;
tmpStream.Seek(0, SeekOrigin.Begin);
while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0)
{
request.GetRequestStream().Write(buffer, 0, readed);
}
}
try
{
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;
Global.Logger.Debug("BoxApp: save file response - " + result);
}
}
catch (WebException e)
{
Global.Logger.Error("BoxApp: Error save file", e);
request.Abort();
var httpResponse = (HttpWebResponse)e.Response;
if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
{
throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
}
throw;
}
}