我有一个我需要使用文件的web服务。问题是这个webservice将API调用限制为100MB,但文件大于100MB。所以他们建议我们使用Range标头。我将范围添加到HttpWebRequest。我的问题似乎是将Streams结合起来。我认为这源于我无法创建ConnectSream的实例(我认为是GetResponseStream返回的实例)。所以我必须创建一个MemoryStream。除非我这样做,我尝试打开一个测试zip文件,我上传它不会打开。我将下载的文件与原始副本进行了比较,下载的文件中没有实际数据,在十六进制视图中显示全部为0。我该如何解决这个问题,以便将两个流组合起来然后将文件保存到磁盘中?
foreach (var largeFile in LargeFilesToDownload)
{
Stream stream = new MemoryStream();
while (endSize <= largeFile.Value)
{
try
{
HttpWebRequest downReq = (HttpWebRequest)HttpWebRequest.Create("https://webserviceurl/" + largeFile.Key);
downReq.Headers.Add("Authorization", "Bearer " + API_TOKEN);
downReq.AddRange(startSize, endSize);
downReq.Method = "GET";
using (var eresp2 = (HttpWebResponse)downReq.GetResponse())
{
eresp2.GetResponseStream().CopyTo(stream);
}
}
catch (Exception exc)
{
//Handle Exception
}
//Set new startSize and endSize here
}
try
{
//check to make sure path exists here
string path = SaveLocation + @"\" + rootDir + @"\" + Path.GetFileName(largeFile.Key);
using (FileStream file = new FileStream(path, FileMode.Create, System.IO.FileAccess.Write))
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
file.Write(bytes, 0, bytes.Length);
stream.Close();
}
FilesToDelete.Add(largeFile.Key);
}
catch (Exception ex2)
{
//Handle Exception
}
}