通过HttpWebRequest C#将多个远程文件复制到另一个远程文件

时间:2017-07-19 11:18:52

标签: c# stream httpwebrequest httpwebresponse

我有一个带有 n 文件的远程文件夹,我需要在另一个远程文件中复制内容。我想它可以通过流完成,这就是我尝试过的:

            WebRequest destRequest = WebRequest.Create(destFile);
            destRequest.Method = "PUT";
            destRequest.Headers.Add("x-ms-blob-type", "BlockBlob"); //just an example with Azure blob, doesn't matter


            using (Stream destStream = destRequest.GetRequestStream())
            {
                string sourceName = "mysourcefolder";

                int blockSize = 8388608; //all the files have the same lenght, except one (sometimes)
                for (int i = 0; i < n; i++)
                {
                    string source = sourceName + i;
                    WebRequest sourceRequest = WebRequest.Create(source);
                    destRequest.Method = "GET";
                    HttpWebResponse destResp = (HttpWebResponse)destRequest.GetResponse();
                    using (Stream sourceStream = destResp.GetResponseStream())
                    {
                        sourceStream.CopyTo(destStream, blockSize);
                    }
                }

                Console.Write("ok");
            }

        }
        catch (Exception e)
        {
            Console.Write("nope !");
        }

我的代码中存在多个问题:

1)我必须在PUT请求中指定长度。可能是blockSize*n,因为我对此没有例外;

2)如果是这种情况,我仍然有例外Cannot close stream until all bytes are written。这是什么意思?

1 个答案:

答案 0 :(得分:1)

资源和目标请求存在混淆。 我已经对变化的线条添加了评论。

        WebRequest destRequest = WebRequest.Create(destFile);
        destRequest.Method = "PUT";
        destRequest.Headers.Add("x-ms-blob-type", "BlockBlob"); //just an example with Azure blob, doesn't matter
        using (Stream destStream = destRequest.GetRequestStream())
        {
            string sourceName = "mysourcefolder";
            //int blockSize = 8388608; //all the files have the same lenght, except one (sometimes) //all the files have the same lenght, except one (sometimes)
            for (int i = 0; i < n; i++)
            {
                string source = sourceName + i;
                WebRequest sourceRequest = WebRequest.Create(source);
                destRequest.Method = "GET";

                //HttpWebResponse destResp = (HttpWebResponse)destRequest.GetResponse();
                //using (Stream sourceStream = destResp.GetResponseStream())

                // you need source response
                HttpWebResponse sourceResp = (HttpWebResponse)sourceRequest.GetResponse();
                using (Stream sourceStream = sourceResp.GetResponseStream())
                {
                    sourceStream.CopyTo(destStream);
                }
            }
            // The request is made here
            var destinationResponse = (HttpWebResponse) destRequest.GetResponse();
            //Console.Write("ok");
            Console.Write(destinationResponse.StatusCode.ToString());
        }